Spring Boot 整合 Thymeleaf 模板引擎:从零开始的完整指南
引言:为什么选择 Thymeleaf?
Thymeleaf 是一个现代化的服务器端 Java 模板引擎,专为 Web 开发而设计。与 JSP 不同,Thymeleaf 模板是纯 HTML 文件,可以直接在浏览器中预览,无需后端服务器支持。这种"自然模板"特性让前端开发和后端开发可以无缝协作。Spring Boot 官方推荐使用 Thymeleaf 作为视图技术,它提供了:
-
简洁优雅的语法
-
强大的表达式语言
-
与 Spring 生态的完美集成
-
丰富的布局功能
-
开箱即用的国际化支持
本文将带你从零开始,全面掌握 Spring Boot 中 Thymeleaf 的使用。
一、环境搭建
1. 创建 Spring Boot 项目
使用 Spring Initializr (https://start.spring.io/) 创建项目,选择以下依赖:
-
Spring Web
-
Thymeleaf
2. Maven 依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
</dependencies>
3. 目录结构
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── controller
│ │ ├── model
│ │ └── DemoApplication.java
│ └── resources
│ ├── static # 静态资源(CSS, JS, 图片)
│ ├── templates # Thymeleaf 模板
│ └── application.properties
二、基础配置
application.properties 配置
# Thymeleaf 配置
spring.thymeleaf.cache=false # 开发时关闭缓存
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8# 静态资源路径
spring.resources.static-locations=classpath:/static/
三、第一个 Thymeleaf 页面
1. 创建控制器
@Controller
public class HomeController {@GetMapping("/")public String home(Model model) {model.addAttribute("message", "Hello, Thymeleaf!");model.addAttribute("currentDate", new Date());return "home"; // 对应 templates/home.html}
}
2. 创建模板文件 (templates/home.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Thymeleaf 入门</title>
</head>
<body><h1 th:text="${message}">默认标题</h1><p>当前时间:<span th:text="${#dates.format(currentDate, 'yyyy-MM-dd HH:mm:ss')}"></span></p><!-- 使用 Thymeleaf 表达式 --><div th:if="${not #strings.isEmpty(message)}"><p>消息长度:<span th:text="${#strings.length(message)}"></span></p></div><!-- 链接表达式 --><a th:href="@{/about}">关于我们</a>
</body>
</html>
3. 运行并访问
启动应用后访问 http://localhost:8080,你将看到:
-
"Hello, Thymeleaf!" 标题
-
格式化的当前时间
-
消息长度计算
-
指向关于页面的链接
四、Thymeleaf 核心语法
1. 变量表达式 (${...})
用于访问模型中的数据:
<p th:text="${user.name}">用户名</p>
<p th:text="${user.age > 18 ? '成年' : '未成年'}">年龄状态</p>
2. 选择表达式 (*{...})
与 th:object
配合使用:
<div th:object="${user}"><p>姓名: <span th:text="*{name}"></span></p><p>邮箱: <span th:text="*{email}"></span></p>
</div>
3. 消息表达式 (#{...})
用于国际化:
<p th:text="#{welcome.message}">欢迎信息</p>
4. 链接表达式 (@{...})
生成正确的 URL:
<a th:href="@{/users/{id}/profile(id=${userId})}">用户资料</a>
<img th:src="@{/images/logo.png}">
5. 片段表达式 (~{...})
包含模板片段:
<div th:insert="~{fragments/header :: header}"></div>
五、常用功能详解
1. 条件判断
<div th:if="${user.isAdmin}"><button>管理面板</button>
</div><div th:unless="${user.active}"><p class="warning">账户未激活</p>
</div><div th:switch="${user.role}"><p th:case="'admin'">管理员</p><p th:case="'user'">普通用户</p><p th:case="*">未知角色</p>
</div>
2. 循环遍历
<table><tr th:each="user, iterStat : ${users}"><td th:text="${iterStat.index + 1}">序号</td><td th:text="${user.name}">姓名</td><td th:text="${user.email}">邮箱</td><td><span th:if="${user.active}" th:text="激活"></span><span th:unless="${user.active}" th:text="未激活"></span></td></tr>
</table>
3. 表单处理
<form th:action="@{/users}" th:object="${user}" method="post"><input type="text" th:field="*{name}" placeholder="姓名"><input type="email" th:field="*{email}" placeholder="邮箱"><button type="submit">保存</button><!-- 显示字段错误 --><div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="error"></div>
</form>
4. 布局模板
layout.html (布局文件)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title th:text="${title}">默认标题</title><th:block th:replace="fragments/head :: head"></th:block>
</head>
<body><header th:replace="fragments/header :: header"></header><main><!-- 内容区域 --><div th:replace="${view}"></div></main><footer th:replace="fragments/footer :: footer"></footer>
</body>
</html>
home.html (具体页面)
<!DOCTYPE html>
<html th:replace="~{layout :: layout(~{::title}, ~{::main})}">
<head><title>首页</title>
</head>
<body><main><h1>欢迎来到首页</h1><p>这是主要内容区域</p></main>
</body>
</html>
六、实用技巧与最佳实践
1. 工具对象
Thymeleaf 提供了一系列实用工具:
-
#dates
:日期格式化 -
#strings
:字符串操作 -
#numbers
:数字格式化 -
#lists
:集合操作 -
#arrays
:数组操作 -
#objects
:对象操作<p th:text="${#dates.format(user.birthday, 'yyyy年MM月dd日')}"></p> <p th:text="${#strings.capitalize(user.name)}"></p> <p th:text="${#lists.size(user.roles)}"></p>
2. 内联表达式
使用 [[...]]
或 [(...)]
在 HTML 属性中内联表达式:
<script th:inline="javascript">var userId = [[${user.id}]];var userName = /*[[${user.name}]]*/ '默认名称';
</script><p data-user-id="${user.id}">用户ID: [[${user.id}]]</p>
3. 模板缓存管理
开发环境关闭缓存,生产环境开启缓存:
# application-dev.properties
spring.thymeleaf.cache=false# application-prod.properties
spring.thymeleaf.cache=true
4. 自定义方言
创建自定义 Thymeleaf 处理器:
public class AlertDialect extends AbstractProcessorDialect {public AlertDialect() {super("Alert Dialect", "alert", 1000);}@Overridepublic Set<IProcessor> getProcessors(String dialectPrefix) {return Set.of(new AlertTagProcessor(dialectPrefix));}
}public class AlertTagProcessor extends AbstractElementTagProcessor {// 实现自定义标签处理逻辑
}
注册方言:
@Configuration
public class ThymeleafConfig {@Beanpublic AlertDialect alertDialect() {return new AlertDialect();}
}
七、常见问题解决
1. 静态资源加载问题
确保路径正确:
<!-- 正确方式 -->
<link th:href="@{/css/style.css}" rel="stylesheet"><!-- 错误方式 -->
<link href="/css/style.css" rel="stylesheet">
2. 表单绑定失败
确保表单对象和字段名匹配:
// Controller
@PostMapping("/save")
public String saveUser(@ModelAttribute("userForm") User user) {// ...
}
<!-- 模板 -->
<form th:object="${userForm}"><input th:field="*{name}">
</form>
3. 国际化支持
配置消息源:
# application.properties
spring.messages.basename=messages
创建 messages.properties:
welcome.message=欢迎您, {0}!
在模板中使用:
<p th:text="#{welcome.message(${user.name})}"></p>
八、进阶学习资源
-
官方文档:
-
Thymeleaf 官方文档
-
Spring Boot Thymeleaf 文档
-
-
推荐书籍:
-
"Thymeleaf: Practical Natural Templates" by José Samper
-
"Spring Boot in Action" by Craig Walls
-
-
实战项目:
-
GitHub 搜索 "spring-boot-thymeleaf-example"
-
Spring 官方示例项目
-
总结
Thymeleaf 作为 Spring Boot 的官方推荐模板引擎,提供了强大的功能和优雅的语法。通过本文的学习,你应该能够:
-
搭建 Spring Boot + Thymeleaf 开发环境
-
使用基础表达式和常用功能
-
实现复杂的页面布局
-
处理表单和验证
-
解决常见开发问题
Thymeleaf 的"自然模板"特性使其成为现代 Web 开发的理想选择,它让前后端协作更加高效。现在就开始在你的项目中尝试使用 Thymeleaf 吧!