在 Spring Boot 开发中,动态页面渲染是常见需求。相比传统的 JSP,Thymeleaf 模板引擎以其“动静结合”的特性(无需启动服务器即可预览静态页面)成为 Spring 官方推荐的方案。
一、Thymeleaf 是什么?为什么选择它?
Thymeleaf 是一款现代化的服务器端 Java 模板引擎,支持 HTML、XML、TEXT 等多种格式。它的核心优势在于:
- 动静兼容:模板文件可直接在浏览器中打开(显示静态内容),启动服务器后自动替换为动态数据,方便前后端协作。
- 无需标签库:基于 HTML 原生属性扩展(如
th:text
),语法直观,学习成本低。 - Spring 生态适配:与 Spring Boot 深度整合,自动配置,开箱即用。
Spring Boot 项目中引入 Thymeleaf 后,无需额外配置即可使用,极大简化了动态页面开发流程。
二、快速入门
步骤 1:添加依赖
在 pom.xml
中引入 Thymeleaf 起步依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Spring Boot 会自动配置 Thymeleaf 相关组件,无需手动设置。
步骤 2:创建模板文件
在 src/main/resources/templates
目录下创建 index.html
(Thymeleaf 模板默认存放目录):
<!DOCTYPE html>
<!-- 引入 Thymeleaf 命名空间,支持语法提示 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf 入门</title>
</head>
<body>
<!-- 静态页面显示"默认欢迎语",动态时替换为后端数据 -->
<h2 th:text="${msg}">默认欢迎语</h2>
</body>
</html>
th:text
:Thymeleaf 核心属性,用于将后端传递的msg
变量值替换标签内容。- 未启动服务器时,浏览器直接显示“默认欢迎语”;启动后显示动态数据。
步骤 3:编写控制器
@Controller
public class PageController {
@GetMapping("/show")
public String showPage(Model model) {
// 向模板传递数据(键为"msg",值为"Hello Thymeleaf")
model.addAttribute("msg", "Hello Thymeleaf");
return "index"; // 跳转至 templates/index.html
}
}
- 控制器通过
Model
传递数据,Thymeleaf 模板通过${键名}
引用。 - 返回字符串
index
表示渲染templates/index.html
模板。
步骤 4:测试
启动项目后访问 http://localhost:8080/show
,页面会显示 Hello Thymeleaf
,说明整合成功。
三、核心语法: Thymeleaf 常用功能
1. 变量输出
Thymeleaf 通过 th:text
和 th:value
输出变量,分别用于标签文本和表单值:
<!-- 输出文本内容 -->
<span th:text="${username}">默认用户名</span>
<!-- 输出表单值 -->
<input type="text" th:value="${email}">
th:text
:替换标签内的静态文本。th:value
:为input
标签的value
属性赋值。
2. 字符串与日期处理
Thymeleaf 提供内置对象(如 #strings
、#dates
)处理字符串和日期:
字符串操作
<!-- 判断字符串是否为空 -->
<span th:text="${#strings.isEmpty(username)}"></span>
<!-- 字符串长度 -->
<span th:text="${#strings.length(username)}"></span>
<!-- 字符串转大写 -->
<span th:text="${#strings.toUpperCase(username)}"></span>
#strings
包含常见字符串方法(isEmpty
、contains
、substring
等),用法与 Java 字符串方法类似。
日期格式化
<!-- 默认格式化 -->
<span th:text="${#dates.format(now)}"></span>
<!-- 自定义格式(yyyy/MM/dd) -->
<span th:text="${#dates.format(now, 'yyyy/MM/dd')}"></span>
<!-- 提取年份 -->
<span th:text="${#dates.year(now)}"></span>
#dates
用于日期处理,支持格式化、提取年/月/日等操作。
3. 条件判断
通过 th:if
和 th:switch
实现条件逻辑:
th:if
单条件判断
<div th:if="${score >= 60}">
成绩合格
</div>
<div th:if="${score < 60}">
成绩不合格
</div>
th:if
表达式为 true
时显示标签内容。
th:switch
多条件判断
<div th:switch="${role}">
<span th:case="'admin'">管理员</span>
<span th:case="'user'">普通用户</span>
<span th:case="*">未知角色</span> <!-- * 表示默认 -->
</div>
类似 Java 的 switch-case
,th:case="*"
对应 default
。
4. 迭代遍历
使用 th:each
遍历集合(List、Map 等):
遍历 List
<table border="1">
<tr>
<th>ID</th>
<th>姓名</th>
</tr>
<!-- 遍历 users 集合,每个元素赋值给 user 变量 -->
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
</tr>
</table>
遍历 Map
<table border="1">
<tr>
<th>键</th>
<th>值(姓名)</th>
</tr>
<!-- 遍历 map 集合,每个键值对赋值给 m 变量 -->
<tr th:each="m : ${userMap}">
<td th:text="${m.key}"></td>
<td th:text="${m.value.name}"></td> <!-- m.value 为 Map 的值(对象) -->
</tr>
</table>
状态变量
遍历过程中可通过状态变量获取索引、计数等信息:
<tr th:each="user, status : ${users}">
<td th:text="${status.index}"></td> <!-- 索引(从 0 开始) -->
<td th:text="${status.count}"></td> <!-- 计数(从 1 开始) -->
<td th:text="${user.name}"></td>
<td th:text="${status.first}"></td> <!-- 是否为第一个元素 -->
<td th:text="${status.last}"></td> <!-- 是否为最后一个元素 -->
</tr>
status
是状态变量,包含 index
、count
、first
、last
等属性。
5. URL 路径
使用 @{}
生成 URL,支持静态参数、动态参数和 RESTful 风格:
<!-- 静态 URL -->
<a th:href="@{http://www.baidu.com}">百度</a>
<!-- 带静态参数 -->
<a th:href="@{/user?id=1&name=张三}">用户详情</a>
<!-- 带动态参数(后端传递的 id 和 name 变量) -->
<a th:href="@{/user(id=${id}, name=${name})}">用户详情</a>
<!-- RESTful 风格 -->
<a th:href="@{/user/{id}(id=${id})}">用户详情</a>
@{}
会自动处理路径拼接,避免手动拼接字符串的繁琐。
四、Thymeleaf 配置自定义
Spring Boot 对 Thymeleaf 有默认配置,可在 application.yml
中自定义:
spring:
thymeleaf:
prefix: classpath:/templates/ # 模板文件前缀(默认)
suffix: .html # 模板文件后缀(默认)
encoding: UTF-8 # 编码格式
cache: false # 关闭缓存(开发环境推荐)
servlet:
content-type: text/html # 响应类型
cache: false
:关闭模板缓存,修改模板后无需重启项目即可生效(生产环境建议开启)。prefix
和suffix
:指定模板文件的路径和后缀,默认无需修改。
五、常见问题与解决方案
模板无法找到(404)?
- 检查模板文件是否在
src/main/resources/templates
目录下。 - 控制器返回的视图名是否与模板文件名一致(不含
.html
后缀)。
- 检查模板文件是否在
变量无法解析?
- 确认控制器通过
model.addAttribute()
正确传递了变量。 - 检查 Thymeleaf 表达式是否正确(如
${变量名}
拼写是否有误)。
- 确认控制器通过
静态资源(CSS/JS)无法加载?
- 静态资源需放在
src/main/resources/static
目录下(如static/css/style.css
)。 - 模板中通过
/css/style.css
引用(无需包含static
目录)。
- 静态资源需放在
总结
Thymeleaf 作为 Spring Boot 推荐的模板引擎,以其简洁的语法和动静兼容的特性,极大提升了动态页面开发效率。本文从入门案例出发,详解了变量输出、条件判断、迭代遍历等核心功能,并介绍了自定义配置方法,覆盖了日常开发的主要场景。
掌握 Thymeleaf 后,开发者可快速实现动态页面渲染,同时兼顾前后端协作效率。建议在开发环境关闭模板缓存,配合热部署工具(如 DevTools),进一步提升开发体验。