1. 什么是 Thymeleaf
- Thymeleaf 是新一代的 Java 模板引擎,类似于 Velocity、FreeMarker 等传统引擎,其语言和 HTML 很接近,而且扩展性更高;
- Thymeleaf 的主要目的是将优雅的模板引入开发工作流程中,并将 HTML 在浏览器中正确显示。同时能够作为静态引擎,让开发成员之间更方便协作开发;
- Spring Boot 官方推荐使用模板,而且 Spring Boot 也为 Thymeleaf 提供了完整的自动化 配置解决方案;
- Thymeleaf 使用教程请戳 Tutorial: Using Thymeleaf,配合 Spring 使用的教程请戳 Tutorial: Thymeleaf + Spring。
2. 整合过程
2.1 添加 Thymeleaf 依赖
添加 Thymeleaf 依赖有两种方式:
- 在新建项目时添加,在
Templeate Engines
中勾选 Thymeleaf;
- 对于未添加 Thymeleaf 依赖的项目,直接在
pom.xml
中手动添加依赖即可;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.2 编写实体类和 Controller
- 新建实体类
User
package com.cunyu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/**
* @author : cunyu
* @version : 1.0
* @className : Author
* @date : 2020/7/29 16:20
* @description : User 实体类
*/
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int age;
private String name;
private String email;
}
- 编写 Controller
package com.cunyu.controller;
import com.cunyu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author : cunyu
* @version : 1.0
* @className : UserController
* @date : 2020/7/29 16:22
* @description : UserController
*/
@Controller
public class UserController {
// 访问 ip:port/index
@GetMapping("/index")
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
// 设置跳转的视图
modelAndView.setViewName("index");
modelAndView.addObject("title", "Thymeleaf 使用");
modelAndView.addObject("desc", "Spring Boot 整合 Thymeleaf");
User author = new User(25, "村雨遥", "747731461@qq.com");
modelAndView.addObject("author", author);
return modelAndView;
}
}
2.3 创建Thymeleaf 模板
第 2.3 中,设置了跳转的视图为 index
,所以我们需要在 src/main/resources/templates
中创建 index.html
;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}"></title>
</head>
<body>
<h1 th:text="${desc}" th:align="center"></h1>
<h2 th:align="center">=====作者信息=====</h2>
<p th:text="${author?.name}"></p>
<p th:text="${author?.age}"></p>
<p th:text="${author?.email}"></p>
</body>
</html>
2.4 测试
启动项目,然后在浏览器中访问 http://localhost:8080/index
,如果出现下图中的信息,说明整合成功。
3. 注意事项
为了方便使用,我们在使用 Thymeleaf 模板时,可以添加一些自己的配置;
# thymelea模板配置
# 设置模板文件存放位置
spring.thymeleaf.prefix=classpath:/templates/
# 设置模板后缀
spring.thymeleaf.suffix=.html
# 语法严格限制
spring.thymeleaf.mode=HTML5
# 编码格式
spring.thymeleaf.encoding=UTF-8
# 热部署,每次修改静态页面都不用重启就可以生效,默认为 true
spring.thymeleaf.cache=false