第04课:WebFlux 整合 Thymeleaf

上一篇介绍的是用 MongoDB 来实现 WebFlux 对数据源的操作,那么有了数据需要渲染到前台给用户展示,这就是本文关心的 View 层,View 的表现形式有很多,比如 JSON 和 HTML。开发中常用模板语言很常见的有 Thymeleaf、Freemarker等,那什么是模板语言?

常见的模板语言都包含以下几个概念:数据(Data)、模板(Template)、模板引擎(Template Engine)和结果文档(Result Documents)。

  • 数据

数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。

  • 模板

模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。

  • 模板引擎

模板引擎(这里特指用于 Web 开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的 HTML 文档。

  • 结果文档

一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的 HTML 文档。

模板语言用途广泛,常见的用途如下:

  • 页面渲染
  • 文档生成
  • 代码生成
  • 所有 “数据+模板=文本” 的应用场景

Spring Boot 推荐使用的模板语言是 Thymeleaf,那什么是 Thymeleaf?

官方的解释如下:

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf 是现代的模板语言引擎,可以独立运行也可以服务于 Web,主要目标是为开发提供天然的模板,并且能在 HTML 里面准确的显示。

Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 后推荐使用。目前是 Spring 5 自然更加推荐。

结构

类似上面讲的工程搭建,新建一个工程编写此案例,工程图如图所示:

目录如下:

  • org.spring.springboot.webflux.controller:Controller 层
  • org.spring.springboot.dao:数据操作层 DAO
  • org.spring.springboot.domain:实体类
  • org.spring.springboot.handler:业务逻辑层
  • Application:应用启动类
  • application.properties:应用配置文件
  • pom.xml maven 配置
  • application.properties 配置文件

模板是会用到下面两个目录:

  • static 目录是存放 CSS、JS 等资源文件;
  • templates 目录是存放视图。

本文重点在 Controller 层 和 templates 视图的编写。

新增 POM 依赖与配置

在 pom.xml 配置新的依赖:

  <dependencies>

    <!-- Spring Boot Web Flux 依赖 -->
<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> <!-- Spring Boot Test 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>

这里我们增加了 Thymeleaf 依赖,但不用在 application.properties - 应用配置文件中配置任何配置。默认启动其默认配置,如需修改配置参考 Thymeleaf 依赖配置,如下:

spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

包括常用的编码、是否开启缓存等等。

WebFlux 中使用 Thymeleaf

在 CityWebFluxController 控制层,添加两个方法如下:

    @GetMapping("/hello")
public Mono<String> hello(final Model model) {
model.addAttribute("name", "泥瓦匠");
model.addAttribute("city", "浙江温岭"); String path = "hello";
return Mono.create(monoSink -> monoSink.success(path));
} private static final String CITY_LIST_PATH_NAME = "cityList"; @GetMapping("/page/list")
public String listPage(final Model model) {
final Flux<City> cityFluxList = cityHandler.findAllCity();
model.addAttribute("cityList", cityFluxList);
return CITY_LIST_PATH_NAME;
}

解释下语法:

  • 返回值 Mono<String> 或者 String 都行,但是 Mono<String> 代表着我这个返回 View 也是回调的。
  • return 字符串,该字符串对应的目录在 resources/templates 下的模板名字。
  • Model 对象来进行数据绑定到视图。
  • 一般会集中用常量管理模板视图的路径。

Tymeleaf 视图

然后编写两个视图 hello 和 cityList,代码分别如下。

hello.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<title>欢迎页面</title>
</head> <body> <h1 >你好,欢迎来自<p th:text="${city}"></p>的<p th:text="${name}"></p></h1> </body>
</html>

cityList.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<title>城市列表</title>
</head> <body> <div> <table>
<legend>
<strong>城市列表</strong>
</legend>
<thead>
<tr>
<th>城市编号</th>
<th>省份编号</th>
<th>名称</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr th:each="city : ${cityList}">
<td th:text="${city.id}"></td>
<td th:text="${city.provinceId}"></td>
<td th:text="${city.cityName}"></td>
<td th:text="${city.description}"></td>
</tr>
</tbody>
</table> </div> </body>
</html>

常用语法糖如下:

  • ${...}:变量表达式;
  • th:text:处理 Tymeleaf 表达式;
  • th:each:遍历表达式,可遍历的对象有,实现 java.util.Iterable、java.util.Map(遍历时取 java.util.Map.Entry)、array 等。

还有很多使用,可以参考官方文档

运行工程

下面运行工程验证下,使用 IDEA 右侧工具栏,点击 Maven Project Tab ,点击使用下 Maven 插件的 install 命令;或者使用命令行的形式,在工程根目录下,执行 Maven 清理和安装工程的指令:

cd springboot-webflux-4-thymeleaf
mvn clean install

在控制台中看到成功的输出:

... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2017-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------

在 IDEA 中执行 Application 类启动,任意正常模式或者 Debug 模式,可以在控制台看到成功运行的输出:

... 省略
2018-04-10 08:43:39.932 INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935 INFO 2052 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-04-10 08:43:39.960 INFO 2052 --- [ main] org.spring.springboot.Application : Started Application in 6.547 seconds (JVM running for 9.851)

打开浏览器,访问 http://localhost:8080/city/hello ,可以看到如图的响应:

继续访问 http://localhost:8080/city/page/list , 发现没有值,那么按照上一讲插入几条数据即可有值,如图:

总结

这里探讨了 Spring WebFlux 的如何整合 Thymeleaf,整合其他模板语言 Thymeleaf、Freemarker,就大同小异了。下面,我们可以整合 Thymeleaf 和 MongoBD 来实现一个整体的简单案例。

Spring Boot WebFlux-04——WebFlux 整合 Thymeleaf的更多相关文章

  1. 黑马_13 Spring Boot:04.spring boot 配置文件

    13 Spring Boot: 01.spring boot 介绍&&02.spring boot 入门 04.spring boot 配置文件 05.spring boot 整合其他 ...

  2. spring boot与jdbcTemplate的整合案例2

    简单入门了spring boot后,接下来写写跟数据库打交道的案例.博文采用spring的jdbcTemplate工具类与数据库打交道. 下面是搭建的springbootJDBC的项目的总体架构图: ...

  3. Spring Boot 中使用 MyBatis 整合 Druid 多数据源

    2017 年 10 月 20 日   Spring Boot 中使用 MyBatis 整合 Druid 多数据源 本文将讲述 spring boot + mybatis + druid 多数据源配置方 ...

  4. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  5. Spring Boot数据访问之整合Mybatis

    在Mybatis整合Spring - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中谈到了Spring和Mybatis整合需要整合的点在哪些方面,需要将Mybatis中数据库连接池等相关对 ...

  6. Spring Boot 2.0 WebFlux 教程 (一) | 入门篇

    目录 一.什么是 Spring WebFlux 二.WebFlux 的优势&提升性能? 三.WebFlux 应用场景 四.选 WebFlux 还是 Spring MVC? 五.异同点 六.简单 ...

  7. 实战基于Spring Boot 2的WebFlux和mLab搭建反应式Web

    Spring Framework 5带来了新的Reactive Stack非阻塞式Web框架:Spring WebFlux.作为与Spring MVC并行使用的Web框架,Spring WebFlux ...

  8. spring boot ----> 常用模板freemarker和thymeleaf

    ===========================freemarker=================================== freemarker 官网:https://freem ...

  9. Spring Boot开发Web应用之Thymeleaf篇

    前言 Web开发是我们平时开发中至关重要的,这里就来介绍一下Spring Boot对Web开发的支持. 正文 Spring Boot提供了spring-boot-starter-web为Web开发予以 ...

  10. spring boot(二)整合mybatis plus+ 分页插件 + 代码生成

    先创建spring boot项目,不知道怎么创建项目的 可以看我上一篇文章 用到的环境 JDK8 .maven.lombok.mysql 5.7 swagger 是为了方便接口测试 一.Spring ...

随机推荐

  1. 【maven】pom.xml中"spring-boot-maven-plugin"报红问题

    问题原因 插件下载速度太慢了,即是从国外的中央仓库里下载的. 没有刷新maven spring-boot-maven-plugin没加版本号(有些电脑不加版本号,也是不会爆红的) 问题解决 maven ...

  2. PHP解压压缩包文件到指定目录的实现

    $src_file为文件路径,上传文件返回压缩包路径即可 public function unzip($src_file, $dest_dir=false, $create_zip_name_dir= ...

  3. js实现倒计时函数

    function updateEndTime() { //当前时间,距1970年1月1日的秒数 var date = new Date(); var time = (date.getTime())/1 ...

  4. 狂神说Elasticsearch7.X学习笔记整理

    Elasticsearch概述 一.什么是Elasticsearch? Lucene简介 Lucene是一套用于全文检索和搜寻的开源程序库,由Apache软件基金会支持和提供 Lucene提供了一个简 ...

  5. 在微信框架模块中,基于Vue&Element前端,通过动态构建投票选项,实现单选、复选的投票操作

    最近把微信框架的前端改造一下,在原来基于Bootstrap框架基础上的微信后台管理,增加一套Vue&Element的前端,毕竟Vue的双向绑定开发起来也还是很方便的,而且Element本身也提 ...

  6. Postman(接口自动化测试)

    1.Postman 接口测试参数化可能大家都非常的熟悉,但是很多人很难处理参数化后如何断言的问题,特别是当参数中出现中文时,很容易导致在 Runner 页面引入外部文件时导致中文乱码的问题,今天这篇文 ...

  7. 《Ray Tracing in One Weekend》阅读笔记 - 9、Metal(金属)

    如果我们希望不同的物体使用不同的材料,则需要进行设计决策.我们可以使用具有许多参数的通用材料,而将不同的材料类型仅将其中一些参数归零.这不是一个坏方法.或者我们可以有一个抽象的材料类来封装行为.我是后 ...

  8. [刷题] 167 Two Sum II

    要求 升序数组 找到两个数使得它们相加之和等于目标数 函数返回两个下标值(下标从1开始) 示例 输入:numbers = [2, 7, 11, 15], target = 9 输出:[1,2] 思路 ...

  9. 利用IOzone进行存储性能测试

    利用IOzone进行存储性能测试   命令:1.iozone -s 10G -r 4k -i 0(0代表顺序写) -w(代表文件不删除) -+n(不测重读重写) -Rb(以某种格式生成测试文件) /t ...

  10. Linux_进程管理的基本概述

    一.进程的基本概述 1️⃣:进程是已启动的可执行程序的运行中实例 2️⃣:/proc目录下以数字为名的目录,每一个目录代表一个进程,保存着进程的属性信息 3️⃣:每一个进程的PID是唯一的,就算进程退 ...