一、Thymeleaf 简介
Thymeleaf 是一款现代化的服务器端 Java 模板引擎,主要用于 Web 开发中渲染 HTML 页面,能够无缝集成 Spring Boot 框架。它的核心优势是:
- 支持 HTML 原生语法,模板文件可直接在浏览器中打开预览(无后端数据时显示默认值);
- 与 Spring 生态深度整合,是 Spring Boot 推荐的模板引擎;
- 支持多种表达式、条件判断、循环遍历等动态渲染能力;
- 无静态标签库,语法简洁易懂。
二、环境搭建(Spring Boot 整合)
1. 依赖引入(pom.xml)
xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<dependencies>
<!-- Spring Web 核心依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf 核心依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Lombok(可选,简化实体类) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
2. 核心配置(application.yml)
yaml
server:
port: 8080
spring:
thymeleaf:
cache: false # 开发环境关闭缓存,修改页面无需重启服务
三、Thymeleaf 基础语法
1. 命名空间声明
所有使用 Thymeleaf 的 HTML 页面,需在 <html> 标签中声明命名空间,否则 Thymeleaf 表达式无法生效:
html
预览
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2. 变量表达式(${})
作用
从 Spring 容器的 Model 中获取后端传递的数据,是最常用的表达式。
示例
后端传递数据(Controller)
java
运行
package com.qcby.controller;
import com.qcby.model.People;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Arrays;
import java.util.Date;
@Controller
public class IndexController {
@GetMapping("/basic")
public String basic(Model model) {
// 构建实体类对象
People people = new People();
people.setUsername("renliang");
people.setAge(1);
people.setSex(1);
people.setIsVip(false);
people.setBirthday(new Date());
people.setTags(Arrays.asList("PVP","Node","SUC"));
// 将数据放入Model,key为"people"
model.addAttribute("people", people);
return "basic"; // 跳转到templates下的basic.html
}
}
前端渲染(basic.html)
html
预览
<!-- 直接获取对象属性 -->
<h2 th:text="${people.username}"></h2>
<p th:text="${people.age}"></p>
<!-- 布尔类型判断 -->
<p th:if="${people.isVip}">会员</p>
3. 选择变量表达式(*{})
作用
通过 th:object 指定根对象后,简化属性获取(无需重复写根对象名)。
示例
html
预览
<div th:object="${people}">
<!-- 等价于 ${people.username} -->
<h2 th:text="*{username}"></h2>
<!-- 等价于 ${people.age} -->
<p th:text="*{age}"></p>
</div>
4. 文本替换与拼接
(1)字面量拼接(|${}|)
适用于标题、描述等简单拼接场景:
html
预览
<!-- 默认标题为"默认标题",后端传递title则替换为传递的值 -->
<title th:text="|${title}|">默认标题</title>
<!-- 也可拼接固定文本 -->
<title th:text="|用户中心 - ${people.username}|">用户中心</title>
(2)无转义文本(th:utext)
th:text 会转义 HTML 标签(如 <h1> 变为文本),th:utext 则保留原生 HTML 效果:
java
运行
// Controller 传递带HTML标签的文本
model.addAttribute("hello", "<h1>zhangsan</h1>");
html
预览
<!-- 显示为纯文本:<h1>zhangsan</h1> -->
<div th:text="${hello}"></div>
<!-- 显示为H1标题:zhangsan -->
<div th:utext="${hello}"></div>
5. 条件判断(th:if /th:unless)
作用
根据条件动态渲染元素,th:if 满足条件显示,th:unless 满足条件隐藏(与 th:if 相反)。
示例
html
预览
<!-- 基础条件判断 -->
<a th:href="" th:if="${user.getAge() == 2}" >年龄等于2时显示</a>
<!-- 多条件组合(and/or/not) -->
<p th:if="${user.score >= 60 and user.score < 85}">B</p>
<p th:if="${user.score < 60}">C</p>
<p th:if="${user.score > 85}">优秀</p>
<!-- th:unless 示例(age不等于2时显示) -->
<a th:href="" th:unless="${user.getAge() == 2}" >年龄不等于2时显示</a>
6. 分支选择(th:switch /th:case)
作用
类似 Java 的 switch-case,实现多分支条件渲染,th:case="*" 表示默认分支。
示例
html
预览
<!-- 性别判断:1=男,2=女,其他=默认 -->
<div th:switch="${people.sex}">
<p th:case="1">男</p>
<p th:case="2">女</p>
<p th:case="*">默认</p>
</div>
<!-- 简化版(无默认分支) -->
<span th:switch="${user.gender}">
<p th:case="1">男</p>
<p th:case="2">女</p>
</span>
7. 循环遍历(th:each)
作用
遍历集合(List / 数组等),渲染列表、表格等重复元素,支持获取循环状态(索引、是否第一个 / 最后一个等)。
基础示例(遍历列表)
java
运行
// Controller 传递用户列表
List<User> uList = new ArrayList<>();
for (int i = 0; i < 10; i++){
User u = new User();
u.setUsername("renliang"+i);
u.setPassword("111"+i);
uList.add(u);
}
model.addAttribute("uList", uList);
html
预览
<!-- 遍历uList,a为每个元素,aState为循环状态对象 -->
<table>
<tr th:each="a,aState:${uList}">
<td th:text="${a.username}"></td> <!-- 用户名 -->
<td th:text="${a.password}"></td> <!-- 密码 -->
<td th:text="${aState.index}"></td> <!-- 循环索引(从0开始) -->
</tr>
</table>
循环状态对象常用属性
| 属性 | 说明 |
|---|---|
| index | 索引(从 0 开始) |
| count | 计数(从 1 开始) |
| size | 集合总长度 |
| first | 是否为第一个元素(boolean) |
| last | 是否为最后一个元素(boolean) |
| even/odd | 是否为偶数 / 奇数索引(boolean) |
8. 动态属性(th:attr / 直接绑定)
作用
动态设置 HTML 标签的属性(如 class、href、value 等),推荐直接使用 th:属性名 方式(更简洁)。
示例
html
预览
<!-- 动态设置input的value属性 -->
<input th:value="${user.getUsername()}">
<!-- 动态设置class(三元表达式) -->
<a th:class="${user.getAge() > 2}?'class1':'class2'" >年龄</a>
<!-- 动态设置href(拼接URL) -->
<a th:href="@{/user/detail(id=${user.id})}">用户详情</a>
四、核心注意事项
- 缓存配置 :开发环境务必关闭 Thymeleaf 缓存(
spring.thymeleaf.cache=false),否则修改页面后需重启服务才能生效;生产环境建议开启缓存提升性能。 - 表达式语法 :
- 调用对象方法时需注意参数和返回值(如
user.getAge()而非user.age(),因 Lombok 生成的 getter 方法是getAge()); - 布尔类型判断直接使用
${对象.布尔属性}(如${people.isVip}),无需加== true。
- 调用对象方法时需注意参数和返回值(如
- 模板位置 :Spring Boot 中 Thymeleaf 模板默认放在
src/main/resources/templates目录下,Controller 返回的字符串直接对应模板文件名(无需加.html)。 - 命名空间 :必须在
<html>标签声明xmlns:th="http://www.thymeleaf.org",否则 Thymeleaf 表达式不会被解析。
五、完整示例流程
- 编写实体类(如 People、User),使用 Lombok 的
@Data简化 getter/setter; - 编写 Controller,通过
Model传递数据到模板; - 编写 Thymeleaf 模板,使用上述语法渲染数据;
- 启动 Spring Boot 应用,访问对应接口(如
/basic、/success)查看渲染效果。
例如访问 http://localhost:8080/basic,可看到 People 对象的用户名、年龄、标签列表等数据被动态渲染到页面中;访问 http://localhost:8080/success,可看到用户列表、条件判断、动态属性等效果。