Spring WebFlux中进行页面重定向
一、 背景说明
随着WebFlux技术的成熟,公司在新的技术框架中实践了该技术,本人在使用过程中也记录下一系列实践问题。今天我们要了解的话题,就是如何在Web Flux中进行重定向链接,我们知道在Spring MVC我们通常使用"redirect:xxxx"。但是在Web Flux中却不是这样,下面我们来看看,在Web Flux中它到底是如何进行重定向链接的。
二、 案例实践
2.1 新建WebFlux类型的项目
- Maven依赖如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-web-flux-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-web-flux-example</name>
<description>spring-web-flux-example</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2 编写Controller
@Controller
public class DefaultController
{
/**
* 重定向跳转
*
* @return r
*/
@GetMapping("/test")
public Rendering test()
{
return Rendering.redirectTo("https://www.baidu.com").build();
}
}
2.3 测试效果
在浏览器中输入"localhost:8080/test",回车。我们发现浏览器已经跳转到百度的首页。
2.4 注意事项
Rendering.redirectTo("网址")
:其中填写的网址必须包含协议的。也就是https或http 。如果不填写则会跳转到服务器的内部地址去。