如何在Spring Webflux中重定向请求?

Neo*_*ith 3 spring url-redirection spring-boot spring-webflux

如何在Spring WebFlux中创建重定向Rest Web服务?WebFlux中似乎还没有重定向功能!

我想要这样的东西:

 @Bean
RouterFunction<ServerResponse> monoRouterFunction() {
    return 
        route(GET("/redirect/{id}"),{
            req -> req.Redirect( fetchAUrlFromDataBase() )
        })
Run Code Online (Sandbox Code Playgroud)

Neo*_*ith 5

@Bean
RouterFunction<ServerResponse> routerFunction() {
     route(GET("/redirect"), { req ->
          ServerResponse.temporaryRedirect(URI.create(TargetUrl))
                    .build()
        }
    })

}
Run Code Online (Sandbox Code Playgroud)

非常感谢Johan Magnusson


Jav*_*Net 5

您可以在 Spring boot 主类中添加以下代码,将“/”请求重定向到“/login”页面。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;   

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    @Bean
    RouterFunction<ServerResponse> routerFunction() {
        return  route(GET("/"), req ->
                ServerResponse.temporaryRedirect(URI.create("/login"))
                        .build());
    }
}
Run Code Online (Sandbox Code Playgroud)