一 Thymeleaf是什么
Thymeleaf 是一款现代服务器端 Java 模板引擎,专为 Web 开发设计,尤其适合与 Spring Boot 框架搭配使用。它的核心目标是实现 “自然模板”(Natural Templates)—— 即模板文件本身可直接作为纯 HTML 在浏览器中打开预览,无需依赖服务器渲染,同时能在后端动态填充数据,兼顾开发效率与前端预览体验。
1. 核心定位与优势
-
自然模板特性Thymeleaf 模板以标准 HTML 为基础,通过自定义的
th:*
系列属性(如th:text
、th:if
)实现动态逻辑,而非嵌入特殊标签或脚本。这意味着开发者可直接用浏览器打开模板文件查看静态样式,无需启动后端服务,大幅提升前后端协作效率。示例:静态 HTML 与 Thymeleaf 模板的对比
静态 HTML Thymeleaf 模板 <p>用户名:张三</p>
<p>用户名:<span th:text="${username}">张三</span></p>
(固定文本) ( th:text
动态填充username
,静态预览时显示 “张三”) -
强大的动态渲染能力支持变量输出、条件判断、循环遍历、URL 生成、模板复用等全场景动态逻辑,能覆盖 Web 开发中几乎所有后端渲染需求,且语法简洁直观,易于理解。
-
无缝集成 Spring 生态作为 Spring Boot 官方推荐的模板引擎(默认集成),Thymeleaf 与 Spring MVC、Spring Security 等组件深度兼容,可直接接收 Spring 控制器传递的
Model
数据,无需额外配置,上手成本极低。 -
多模板模式支持除了 HTML,还支持 XML、TEXT、JavaScript、CSS 等多种模板类型,可用于生成邮件内容、配置文件等非 Web 场景,灵活性强。
2.核心工作原理
-
模板文件位置在 Spring Boot 项目中,Thymeleaf 模板默认存放于
src/main/resources/templates
目录下,文件后缀为.html
(或其他支持的类型)。 -
渲染流程
- 前端发送请求到 Spring 控制器(
@Controller
); - 控制器通过
Model
向模板传递动态数据(如model.addAttribute("user", userObj)
); - 控制器返回模板文件名(如
return "index"
,对应templates/index.html
); - Thymeleaf 引擎加载模板,解析
th:*
属性,用Model
中的数据替换动态占位符; - 渲染后的静态 HTML 响应给前端浏览器。
- 前端发送请求到 Spring 控制器(
3.关键语法特点
Thymeleaf 核心通过 “属性” 实现动态逻辑,常用核心属性如下:
- 变量输出:
th:text
(设置元素文本)、th:value
(设置表单元素值),基于$ {变量名}
读取后端数据; - 循环遍历:
th:each
(遍历集合,如th:each="user : ${userList}"
); - 条件判断:
th:if
(条件成立时显示元素)、th:unless
(条件不成立时显示)、th:switch
(多分支判断); - URL 生成:
th:href
(生成链接,如th:href="@{/user/{id}(id=${userId})}"
,自动拼接上下文路径); - 模板复用:
th:fragment
(定义可复用片段)、th:insert
/th:replace
(引入片段,实现导航栏、页脚等公共部分复用)。
二 Thymeleaf怎么用
1.环境准备
1. 创建 Spring Boot 项目
-
使用 Spring Initializr 创建项目,添加依赖:
- Spring Web:提供 Web 支持
- Thymeleaf:模板引擎
- Lombok(可选):简化实体类代码
-
pom.xml
核心依赖:<?xml version="1.0" encoding="UTF-8"?> <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 https://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>2.7.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.yqd</groupId><artifactId>Thymeleaf-Demo</artifactId><version>0.0.1-SNAPSHOT</version><name>Thymeleaf-Demo</name><description>Thymeleaf-Demo</description><properties><java.version>17</java.version></properties><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><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
2.配置文件的修改(application.yml)
spring:application:name: Thymeleaf-Demothymeleaf:cache: falseserver:port: 8080
2. Thymeleaf 基础语法
Thymeleaf 模板文件默认放在 src/main/resources/templates
目录下,后缀为 .html
。
1. 变量输出(${}
)
用于在页面中显示后端传递的变量。
后端 Controller:
package com.yqd.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class ThymeleafController {@GetMapping("/variable")public String variable(Model model) {model.addAttribute("username", "张三");model.addAttribute("age", 20);return "variable"; // 对应templates/variable.html}
}
前端模板(variable.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <!-- 引入Thymeleaf命名空间 -->
<head><title>变量输出</title>
</head>
<body>
<h3>用户名:<span th:text="${username}"></span></h3>
<h3>年龄:<span th:text="${age}"></span></h3>
</body>
</html>
th:text
:将变量值设置为元素的文本内容- 命名空间
xmlns:th="http://www.thymeleaf.org"
用于 IDE 识别 Thymeleaf 语法
2. 对象与集合处理
实体类(User.java):
package com.yqd.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data // Lombok注解,自动生成getter/setter
@AllArgsConstructor
@NoArgsConstructor
public class User {private String name;private Integer age;private String email;
}
后端传递对象和集合:
@GetMapping("/object")
public String object(Model model) {// 单个对象User user = new User();user.setName("李四");user.setAge(25);user.setEmail("lisi@example.com");model.addAttribute("user", user);// 集合List<User> userList = Arrays.asList(new User("王五", 30, "wangwu@example.com"),new User("赵六", 35, "zhaoliu@example.com"));model.addAttribute("userList", userList);return "object";
}
前端模板(object.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>对象与集合</title>
</head>
<body>
<!-- 单个对象 -->
<h3>单个用户信息</h3>
<p>姓名:<span th:text="${user.name}"></span></p>
<p>年龄:<span th:text="${user.age}"></span></p><!-- 集合遍历(th:each) -->
<h3>用户列表</h3>
<ul><li th:each="u : ${userList}"> <!-- u是集合中的每个元素 -->姓名:<span th:text="${u.name}"></span>,邮箱:<span th:text="${u.email}"></span></li>
</ul>
</body>
</html>
th:each="变量 : ${集合}"
:遍历集合,变量名可自定义
3. 条件判断(th:if
/th:unless
/th:switch
)
后端传递条件变量:
@GetMapping("/condition")
public String condition(Model model) {model.addAttribute("score", 85);model.addAttribute("role", "admin");return "condition";
}
前端模板(condition.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>条件判断</title>
</head>
<body>
<!-- th:if:条件为true时显示 -->
<p th:if="${score >= 60}">成绩合格</p>
<!-- th:unless:与th:if相反,条件为false时显示 -->
<p th:unless="${score >= 90}">未达到优秀</p><!-- th:switch/th:case:类似Java的switch -->
<div th:switch="${role}"><p th:case="'admin'">您是管理员</p><p th:case="'user'">您是普通用户</p><p th:case="*">未知角色</p> <!-- *表示默认 -->
</div>
</body>
</html>
4. 链接与表单
后端处理请求:
@GetMapping("/link")
public String link(Model model) {model.addAttribute("id", 100);return "link";
}// 处理表单提交
@PostMapping("/submit")
public String submit(@RequestParam String username, Model model) {model.addAttribute("msg", "提交成功!用户名:" + username);return "result";
}
前端模板(link.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>链接与表单</title>
</head>
<body>
<a href="/variable">原始跳转方式</a>
<!-- 链接(th:href) -->
<a th:href="@{/variable}">跳转到变量页面</a>
<br>
<a th:href="@{/user/{id}(id=${id})}">带参数的链接(id=100)</a> <!-- 路径参数 --><!-- 表单(th:action/th:method) -->
<form th:action="@{/submit}" th:method="post">用户名:<input type="text" name="username"><button type="submit">提交</button>
</form>
</body>
</html>
前端模板(result.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <!-- 引入Thymeleaf命名空间 -->
<head><title>result页面</title>
</head>
<body>
<span th:text="${msg}">hello</span>
</body>
</html>
@{}
:用于生成 URL,自动拼接上下文路径(避免硬编码)- 表单提交需注意:
th:method
支持get
/post
,参数通过name
属性绑定
5. 内置对象与工具类
Thymeleaf 提供了常用内置对象(如请求参数、会话)和工具类(如日期格式化)。
后端传递数据:
@GetMapping("/utility")
public String utility(Model model, HttpSession session) {model.addAttribute("date", new Date());session.setAttribute("loginUser", "admin"); // 会话对象return "utility";
}
前端模板(utility.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>内置对象与工具类</title>
</head>
<body>
<!-- 请求参数(param对象) -->
<p>URL参数name:<span th:text="${param.name}"></span></p>
<!-- 访问:http://localhost:8080/utility?name=test 可看到结果 --><!-- 会话对象(session对象) -->
<p>登录用户:<span th:text="${session.loginUser}"></span></p><!-- 日期格式化(#dates工具类) -->
<p>原始日期:<span th:text="${date}"></span></p>
<p>格式化日期:<span th:text="${#dates.format(date, 'yyyy-MM-dd HH:mm:ss')}"></span></p><!-- 字符串工具类(#strings) -->
<p>字符串长度:<span th:text="${#strings.length('hello')}"></span></p>
<p>字符串大写:<span th:text="${#strings.toUpperCase('hello')}"></span></p>
</body>
</html>
- 常用内置对象:
param
(请求参数)、session
(会话)、application
(应用上下文) - 常用工具类:
#dates
(日期)、#strings
(字符串)、#numbers
(数字)
6. 模板复用(th:fragment
/th:insert
/th:replace
)
用于抽取公共部分(如导航栏、页脚),减少重复代码。
后端传递数据:
@GetMapping("/reuse")
public String utility() {return "reuse";
}
公共模板(common/footer.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<!-- 定义片段 -->
<div th:fragment="footer"><p>© 2025 我的网站 版权所有</p>
</div>
</body>
</html>
使用公共片段的页面(reuse.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>模板复用</title>
</head>
<body>
<h3>主内容</h3>
<!-- 引入公共片段 -->
<div th:insert="~{common/footer :: footer}"></div>
<!-- 或使用th:replace(替换当前标签) -->
<!-- <div th:replace="~{common/footer :: footer}"></div> -->
</body>
</html>
th:fragment="片段名"
:定义可复用片段th:insert="~{模板路径 :: 片段名}"
:插入片段(保留当前标签)th:replace="~{模板路径 :: 片段名}"
:替换当前标签为片段
三、运行与测试
- 启动 Spring Boot 应用(主类添加
@SpringBootApplication
注解) - 访问以下地址测试各功能:
- 变量输出:http://localhost:8080/variable
- 对象与集合:http://localhost:8080/object
- 条件判断:http://localhost:8080/condition
- 链接与表单:http://localhost:8080/link
- 内置对象:http://localhost:8080/utility?name=test
- 模板复用:http://localhost:8080/reuse
四、总结
Thymeleaf 的核心优势是自然模板(模板文件可直接作为 HTML 打开),常用语法包括:
- 变量输出:
${}
+th:text
- 遍历:
th:each
- 条件:
th:if
/th:unless
/th:switch
- URL 生成:
@{}
- 模板复用:
th:fragment
+th:insert