1. 基础取值:变量表达式 ${...}
这是最常用的语法,用于从后端 Controller 传递的 Model 中获取数据。
-
后端代码:
1@GetMapping("/test")
2public String test(Model model) {
3 model.addAttribute("name", "张三");
4 model.addAttribute("user", new User("李四", 25));
5 return "index";
6} -
前端页面(index.html):
1
2默认值
3
4姓名
5年龄
2. 表单绑定与回显:th:object 与 th:field
在修改或新增数据时,这套组合拳能让表单自动填充数据,并在提交时自动封装到后端实体类中。
-
后端代码:
1// 编辑页面,将查到的用户塞入模型
2model.addAttribute("user", userService.getById(1)); -
前端页面:
1<form th:action="@{/update}" th:object="${user}" method="post">
2
3
4
5
6 <label>姓名:</label>
7
8
9 <button type="submit">保存</button>
10</form>
3. 动态链接生成:URL 表达式 @{...}
Thymeleaf 处理 URL 极其强大,能自动带上项目的上下文路径(Context Path),并且完美支持参数拼接。
4. 循环遍历:th:each
用于渲染表格、下拉框等重复结构。
-
后端代码:
1List<User> userList = userService.list();
2model.addAttribute("users", userList); -
前端页面:
1
2
3序号 姓名 操作
4
5
6
7
8
9
10
11
12 删除
13
14
15
5. 条件判断与逻辑运算:th:if / th:unless
控制页面元素的显示与隐藏。
-
判空与非空:
1
2暂无数据
3
4 -
三元运算符与 Elvis 运算符(防止空指针):
1
2
3
4
6. 常用工具对象(内置神器)
Thymeleaf 提供了一系列以 # 开头的工具类,专门用来处理格式化。
-
日期格式化(解决你之前遇到的时间戳问题):
1
2 -
字符串处理:
1
2
7. 页面布局复用:th:fragment 与 th:replace
避免每个页面都重复写导航栏和页脚。
-
定义公共片段(common/header.html):
1
2我的网站标题
3
4 -
在主页面引用:
1
2