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

6

我该如何在Spring WebFlux中创建重定向REST Web服务?目前似乎WebFlux还没有重定向功能!

我需要像这样的东西:

 @Bean
RouterFunction<ServerResponse> monoRouterFunction() {
    return 
        route(GET("/redirect/{id}"),{
            req -> req.Redirect( fetchAUrlFromDataBase() )
        })
3个回答

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

}

非常感谢Johan Magnusson


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());
    }
}

2
我使用下面的代码片段实现了这一点。 我向渲染函数传递了一个重定向字符串。
下面的代码将重定向到登录路线。
ServerResponse.ok().render("redirect:/login")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接