thymeleaf模板引擎
Thymeleaf 是 SpringBoot 推荐的服务端模板引擎,能在 HTML 中直接嵌入表达式、循环、条件判断等逻辑,同时保持页面 “纯 HTML 可预览” 的特性(无需启动服务也能看静态效果)。
引入thymeleaf
在 SpringBoot 项目中引入 Thymeleaf 只需两步:
步骤 1:添加依赖(Maven 示例)
在 pom.xml 中加入 Thymeleaf 启动器依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
步骤 2:了解默认配置(由 ThymeleafProperties 管理)
SpringBoot 对 Thymeleaf 做了默认配置,核心规则:
- 模板文件默认存放在
classpath:/templates/目录下; - 模板文件后缀默认是
.html; - 配置前缀可通过
spring.thymeleaf.prefix修改,后缀可通过spring.thymeleaf.suffix修改(如自定义模板目录为classpath:/views/,可在application.properties中配置:spring.thymeleaf.prefix=classpath:/views/)。
thymeleaf语法
Thymeleaf 语法通过 “属性前缀 th:” 在 HTML 标签中嵌入逻辑,以下是核心语法及示例:
- 变量表达式
${...}:获取模型数据
用于从SpringMVC传递的 Model 中获取数据
**示例:**Controller 传递用户信息到页面。
// Controller 代码
@GetMapping("/user")
public String getUser(Model model) {User user = new User(1, "张三", 25);model.addAttribute("user", user);return "user"; // 对应 templates/user.html
}// 实体类 User
public class User {private Integer id;private String name;private Integer age;// 省略 getter/setter和构建器
}
<!-- templates/user.html -->
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>用户信息</title>
</head>
<body><!-- 直接获取 user 对象的属性 --><p>ID:<span th:text="${user.id}"></span></p><p>姓名:<span th:text="${user.name}"></span></p><p>年龄:<span th:text="${user.age}"></span></p>
</body>
</html>
-
选择表达式
*{...}:基于对象选择属性需先通过
th:object指定 “对象上下文”,再在内部用*{属性名}读取,适合对象属性较多的场景。**示例:**优化用户信息展示,用选择表达式简化代码。
<!-- templates/user.html 优化后 --> <!DOCTYPE html> <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>用户信息</title> </head> <body><!-- 先指定对象上下文为 user --><div th:object="${user}"><p>ID:<span th:text="*{id}"></span></p><p>姓名:<span th:text="*{name}"></span></p><p>年龄:<span th:text="*{age}"></span></p></div> </body> </html> -
链接表达式
@{...}:生成 URL用于生成绝对 / 相对 URL,自动处理上下文路径(避免硬编码)。
**示例:**页面中添加跳转链接、资源引用。
<!-- 生成页面跳转链接 --> <a th:href="@{/index}">返回首页</a><!-- 引入静态资源(如 CSS、JS) --> <link rel="stylesheet" th:href="@{/css/style.css}"> <script th:src="@{/js/main.js}"></script><!-- 带参数的 URL --> <a th:href="@{/user/detail(id=${user.id})}">查看详情</a> -
条件判断
th:if/th:unless/th:switch:控制元素显示th:if:条件为true时显示元素;th:unless:条件为false时显示元素(与th:if相反);th:switch+th:case:多分支判断。
**示例:**根据用户年龄显示不同提示。
<div th:object="${user}"><!-- th:if 示例:年龄≥18 显示“成年” --><p th:if="*{age} >= 18">您已成年</p><!-- th:unless 示例:年龄<18 显示“未成年” --><p th:unless="*{age} >= 18">您未成年</p><!-- th:switch 示例:根据年龄区间提示 --><div th:switch="*{age}"><p th:case="18">刚成年</p><p th:case="25">青年</p><p th:case="*">其他年龄</p></div> </div> -
循环遍历
th:each:遍历集合 / 数组用于遍历 List、Map、数组等,可获取元素、索引、状态(是否第一个 / 最后一个等)。
**示例:**展示用户列表。
// Controller 传递用户列表 @GetMapping("/user/list") public String getUserList(Model model) {List<User> userList = Arrays.asList(new User(1, "张三", 25),new User(2, "李四", 30),new User(3, "王五", 22));model.addAttribute("userList", userList);return "user-list"; }<!-- templates/user-list.html --> <!DOCTYPE html> <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>用户列表</title> </head> <body><table border="1"><tr><th>序号</th><th>ID</th><th>姓名</th><th>年龄</th><th>状态</th></tr><!-- 遍历 userList,status 是状态变量(包含索引、是否第一个等) --><tr th:each="user, status : ${userList}"><td th:text="${status.index + 1}"></td> <!-- 索引从 0 开始,+1 后显示序号 --><td th:text="${user.id}"></td><td th:text="${user.name}"></td><td th:text="${user.age}"></td><td th:text="${status.first ? '第一个' : (status.last ? '最后一个' : '中间项')}"></td></tr></table> </body> </html> -
内置对象:简化常用操作
Thymeleaf 提供了大量内置对象(如
#strings、#numbers、#dates等),用于字符串、数字、日期的格式化。**示例:**格式化日期、字符串拼接。
<div th:object="${user}"><!-- 假设 user 有 birthday 字段(Date 类型) --><p>生日:<span th:text="${#dates.format(*{birthday}, 'yyyy-MM-dd')}"></span></p><!-- 字符串拼接 --><p>信息:<span th:text="'姓名:' + *{name} + ',年龄:' + *{age}"></span></p><!-- 字符串工具:判断非空、转大写 --><p th:if="${#strings.isEmpty(*{name})}">姓名为空</p><p>姓名大写:<span th:text="${#strings.toUpperCase(*{name})}"></span></p> </div> -
表单与数据绑定(
th:field)在前后端交互中,表单提交是高频场景,Thymeleaf 的
th:field可简化表单字段与模型的绑定。**示例:**用户注册表单,自动绑定实体类字段。
// 实体类 UserForm public class UserForm {private String username;private String password;private Integer age;// 省略 getter/setter }// Controller 代码 @GetMapping("/register") public String register(Model model) {model.addAttribute("userForm", new UserForm());return "register"; }@PostMapping("/register") public String doRegister(@ModelAttribute UserForm userForm) {// 处理表单提交逻辑return "success"; }<!-- templates/register.html --> <!DOCTYPE html> <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>用户注册</title> </head> <body><form th:action="@{/register}" th:object="${userForm}" method="post"><!-- th:field 自动绑定 username 字段,包含 name、id、value --><input type="text" th:field="*{username}" placeholder="请输入用户名"><br><input type="password" th:field="*{password}" placeholder="请输入密码"><br><input type="number" th:field="*{age}" placeholder="请输入年龄"><br><button type="submit">提交</button></form> </body> </html> -
国际化(多语言支持)
Thymeleaf 可结合 SpringBoot 实现页面多语言切换,核心是配置
messages_xx.properties资源文件。-
步骤 1:配置国际化资源文件
在
resources目录下创建:-
messages.properties(默认语言):user.name=姓名 user.age=年龄 button.submit=提交 -
messages_en.properties(英文):user.name=Name user.age=Age button.submit=Submit
-
-
步骤 2:页面中使用国际化文本
<!DOCTYPE html> <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>国际化示例</title> </head> <body><!-- 直接使用国际化 key --><p th:text="#{user.name}">姓名</p><p th:text="#{user.age}">年龄</p><button th:text="#{button.submit}">提交</button><!-- 切换语言的链接(通过参数指定 locale) --><a th:href="@{/page(locale=zh_CN)}">中文</a><a th:href="@{/page(locale=en)}">English</a> </body> </html> -
步骤 3:配置 SpringBoot 支持国际化
在
application.properties中添加:spring.messages.basename=messages spring.mvc.locale-resolver=fixed # 或用 Cookie、Session 方式,根据需求选择
-
-
自定义工具类(
Dialect扩展)如果内置对象满足不了需求,可自定义 Thymeleaf 工具类,通过
Dialect扩展语法。**示例:**自定义字符串脱敏工具。
// 自定义工具类 public class MyUtils {public String maskPhone(String phone) {if (phone == null || phone.length() < 11) return phone;return phone.substring(0, 3) + "****" + phone.substring(7);} }// 注册 Dialect @Configuration public class ThymeleafConfig {@Beanpublic MyDialect myDialect() {return new MyDialect();} }class MyDialect extends AbstractProcessorDialect {public MyDialect() {super("My Dialect", "my", 1000);}@Overridepublic Set<IProcessor> getProcessors(String dialectPrefix) {Set<IProcessor> processors = new HashSet<>();processors.add(new MyUtilityExpressionObjectFactory(dialectPrefix));return processors;} }class MyUtilityExpressionObjectFactory extends AbstractUtilityExpressionObjectFactory {public MyUtilityExpressionObjectFactory(String dialectPrefix) {super(dialectPrefix);}@Overrideprotected Map<String, Object> createObjectMap() {Map<String, Object> map = new HashMap<>();map.put("myUtils", new MyUtils()); // 注册工具类,页面中通过 ${#myUtils.xxx} 调用return map;} }<!-- 页面中使用自定义工具 --> <p>脱敏手机号:<span th:text="${#myUtils.maskPhone('13800138000')}"></span></p> -
性能与缓存配置
在生产环境中,需关注 Thymeleaf 的缓存和性能,可通过配置调整:
# 开发环境关闭缓存(便于实时看到模板修改效果) spring.thymeleaf.cache=false# 生产环境开启缓存(提升性能) spring.thymeleaf.cache=true# 模板编码(避免中文乱码) spring.thymeleaf.encoding=UTF-8
