
3.1 整合Thymeleaf
Thymeleaf是新一代Java模板引擎,类似于Velocity、FreeMarker等传统Java模板引擎。与传统Java模板引擎不同的是,Thymeleaf支持HTML原型,既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果。同时,Spring Boot提供了Thymeleaf自动化配置解决方案,因此在Spring Boot中使用Thymeleaf非常方便。Spring Boot整合Thymeleaf主要可通过如下步骤:
1. 创建工程,添加依赖
新建一个Spring Boot工程,然后添加spring-boot-starter-web和spring-boot-starter-thymeleaf依赖,代码如下:

2. 配置Thymeleaf
Spring Boot为Thymeleaf提供了自动化配置类ThymeleafAutoConfiguration,相关的配置属性在ThymeleafProperties类中,ThymeleafProperties部分源码如下:

由此配置可以看到,默认的模板位置在classpath:/templates/,默认的模板后缀为.html。如果使用IntelliJ IDEA工具创建Spring Boot项目,templates文件夹默认就会创建。
当然,如果开发者想对默认的Thymeleaf配置参数进行自定义配置,那么可以直接在application.properties中进行配置,部分常见配置如下:

3. 配置控制器
创建Book实体类,然后在Controller中返回ModelAndView,代码如下:

代码解释:
• 创建Book实体类,承载返回数据。
• 在BookController中,第11~21行构建返回数据,第22~25行创建返回ModelAndView,设置视图名为books,返回数据为所创建的List集合。
4. 创建视图
在resources目录下的templates目录中创建books.html,具体代码如下:

代码解释:
• 首先在第2行导入Thymeleaf的名称空间。
• 第14~18行通过遍历将books中的数据展示出来,Thymeleaf中通过th:each进行集合遍历,通过th:text展示数据。
5. 运行
在浏览器地址栏中输入“http://localhost:8080/books”,即可看到运行结果,如图3-1所示。

图3-1
本节重点介绍Spring Boot整合Thymeleaf,并非Thymeleaf的基础用法,关于Thymeleaf的更多资料,可以查看https://www.thymeleaf.org。