1. Thymeleaf入门:为什么选择它?
第一次接触Thymeleaf是在一个紧急的Web项目重构中,当时团队正被JSP的编译问题和前后端协作效率折磨得焦头烂额。当我发现Thymeleaf的HTML文件可以直接在浏览器中预览时,那种"终于找到救星"的感觉至今难忘。
Thymeleaf作为Spring Boot官方推荐的模板引擎,最吸引我的三个特点是:
自然模板设计:直接在HTML文件中编写,添加
th:前缀的属性(如th:text)就能实现动态渲染。美工设计的静态页面无需修改就能直接使用,后端开发时加上Thymeleaf属性即可变成动态页面。无服务预览:不像JSP必须启动服务器才能查看效果,Thymeleaf模板作为标准HTML,双击就能在浏览器中打开。这对前后端分离开发太友好了!
Spring生态深度整合:自动支持Spring表达式语言(SpEL)、表单绑定、国际化等特性。我常用的一个例子是表单处理:
<form th:action="@{/login}" th:object="${user}" method="post"> <input th:field="*{username}" placeholder="用户名"> <input th:field="*{password}" type="password"> </form>2. 环境搭建:5分钟快速启动
最近在帮新人搭建环境时,我整理了一套最简流程。以IntelliJ IDEA为例:
- 创建Spring Boot项目:
- 勾选
Spring Web和Thymeleaf依赖 - 或者手动添加pom.xml依赖:
- 勾选
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>目录结构关键点:
src/main/resources ├── static/ # 静态资源(CSS/JS) └── templates/ # Thymeleaf模板配置调优建议: 在
application.properties中添加:# 开发时关闭缓存,修改即时生效 spring.thymeleaf.cache=false # 建议设置编码(遇到过GBK乱码坑) spring.thymeleaf.encoding=UTF-8
3. 核心语法实战:用户管理页面
去年开发后台管理系统时,我总结了一套Thymeleaf的高频用法:
3.1 数据绑定:用户信息展示
<div th:object="${user}"> <h2>用户详情</h2> <p>姓名:<span th:text="*{name}">张三</span></p> <!-- 日期格式化 --> <p>注册时间: <span th:text="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm')}"> </span></p> </div>提示:
${}用于直接访问模型属性,*{}用于选择当前对象属性
3.2 列表迭代:用户表格
<table class="table"> <tr th:each="user,stat : ${userList}"> <td th:text="${stat.count}">序号</td> <td th:text="${user.name}">姓名</td> <!-- 条件判断 --> <td th:text="${user.vip} ? 'VIP用户' : '普通用户'"></td> </tr> </table>踩坑记录:stat是状态变量,包含index/count/even等有用属性
3.3 表单处理:用户注册
<form th:action="@{/users}" th:object="${user}" method="post"> <!-- 字段绑定 --> <input th:field="*{email}" type="email"> <!-- 错误提示 --> <p th:if="${#fields.hasErrors('email')}" th:errors="*{email}">错误提示</p> </form>实测发现:th:field会自动绑定name/value/id属性
4. 高级技巧:提升开发效率
4.1 模板布局:避免重复代码
定义公共模板layout.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:fragment="common-header"> <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet"> </head> <body> <div th:fragment="header">网站头部</div> <!-- 内容占位 --> <div th:fragment="content"></div> <script th:src="@{/js/jquery.js}"></script> </body> </html>子页面引用:
<html th:replace="~{layout :: html}"> <body> <div th:replace="~{layout :: header}"></div> <div th:insert="~{layout :: content}"> <!-- 页面特有内容 --> </div> </body> </html>4.2 AJAX局部刷新
<div id="user-list" th:fragment="userTable"> <!-- 用户列表内容 --> </div> <script> $('#refresh-btn').click(function(){ $('#user-list').load('/users #user-list'); }); </script>控制器需返回片段:
@GetMapping("/users") public String getUsers(Model model) { model.addAttribute("users", userService.findAll()); return "users :: userTable"; // 只返回userTable片段 }4.3 实用工具函数
这些内置工具我经常用:
<!-- 字符串处理 --> <p th:text="${#strings.substring(user.bio,0,100)} + '...'"></p> <!-- 集合判空 --> <div th:unless="${#lists.isEmpty(comments)}"> <p th:text="'共' + ${#lists.size(comments)} + '条评论'"></p> </div> <!-- 快速创建URL参数 --> <a th:href="@{/search(keywords=${#strings.listJoin(tags,',')})}"> 搜索相关标签 </a>5. 调试技巧与性能优化
开发模式配置:
# 开启模板调试信息 spring.thymeleaf.reactive.full-mode-view-names=* # 禁用缓存 spring.thymeleaf.cache=false缓存优化建议:
- 生产环境务必开启缓存
- 对不常变化的模板使用
th:inline="none"减少解析开销
常见问题排查:
- 页面不更新:检查是否忘记关闭缓存
- 表达式不生效:确保HTML已声明
xmlns:th - 静态资源404:检查是否放在
static/目录下
最近在项目中,我们通过模板片段缓存和资源压缩,使页面加载速度提升了40%。Thymeleaf可能不是性能最高的模板引擎,但它优秀的开发体验和与Spring生态的无缝集成,让它成为我们团队的首选方案。