WebFlux 是一种趋势,作为程序员我们也应该看到未来的趋势,未来的热门技术。我个人感觉 WebFlux 未来会取代 Spring MVC,因此我花了很多的时间和精力在学习 WebFlux。本文我们一起来学习 WebFlux 整合 thymeleaf 吧!
先看一下,我们的运行效果吧!

下面我们开始代码的编写。
WebFlux 整合 thymeleaf 也非常的简单,我们只需要在 spring-boot-starter-webflux 的基础上,再引入 spring-boot-starter-thymeleaf 即可。相关的 pom.xml 文件内容如下:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- thymeleaf 模版引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
然后我们在项目的 src/main/resources/templates/ 下新建一个测试的模板页面 xttblog.html。xttblog.html 页面内容你可以自行规划。
然后,我们在 src/main/resources/ 目录下,新建 application.yml 配置文件。内容如下:
spring:
thymeleaf:
prefix: classpath:/templates/
enabled: true
suffix: .html
cache: false
template-resolver-order: 1
check-template: false
reactive:
max-chunk-size: 8192
最后是 Java 代码,为了方便我就贴到一起了。
@Configuration
public class OAuthWeixinRouter {
@Autowired
private WeixinHandler weixinHandler;
@Bean
public RouterFunction<ServerResponse> webFluxRoutesRegister(){
return RouterFunctions
.route(RequestPredicates.GET("/weixin/login"), weixinHandler::loginPage);
}
}
@Component
public class WeixinHandler {
public Mono<ServerResponse> loginPage(ServerRequest serverRequest) {
Map<String, Object> map = new HashMap<>();
map.put("site", "www.xttblog.com");
map.put("siteName", "");
//返回thymeleaf模版页面
return ServerResponse.ok().render("weixin", map);
}
}
@SpringBootApplication
public class OAuthWeixinApplication {
public static void main(String[] args) {
SpringApplication.run(OAuthWeixinApplication.class, args);
}
}
Ok,到这里,我们的代码就已经写完了,接下来就启动项目,测试测试吧!thymeleaf 中的所有语法和功能都可以在你的 html 中使用。

: » WebFlux 整合 thymeleaf 教程
原创文章,作者:1402239773,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/252003.html