Thymeleaf 模板引擎

需要服务端渲染 HTML(页面里动态填充数据)时,Spring Boot 默认推荐 Thymeleaf:模板是合法的 HTML,浏览器可直接预览,属性以 th: 前缀引入动态能力。

引入与目录约定

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

页面默认放在 src/main/resources/templates/,后缀 .html。控制器返回视图名并填充模型:

@Controller
public class UserPageController {

    @GetMapping("/users/page")
    public String list(Model model) {
        model.addAttribute("users", userService.findAll());
        return "users";          // 渲染 templates/users.html
    }
}

注意这里必须用 @Controller@RestController 会把返回值当 JSON 字符串返回。

常用表达式与属性

  • ${...} 变量表达式:读取 model 数据,如 ${users}${u.name}
  • @{...} URL 表达式:自动拼接上下文路径,如 @{/css/app.css}@{/users/{id}(id=${u.id})}
  • th:text:输出文本内容(自动 HTML 转义,防 XSS);
  • th:if / th:unless:条件渲染;
  • th:each:遍历,可带状态变量拿到序号:th:each="u, st : ${users}"st.count 从 1 开始、st.index 从 0 开始;
  • th:object + *{字段}:先选定对象再写字段,如 th:object="${user}"*{name}

完整示例

templates/users.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
    <tr>
        <th>序号</th>
        <th>ID</th>
        <th>姓名</th>
    </tr>
    <tr th:each="u, st : ${users}">
        <td th:text="${st.count}">1</td>
        <td th:text="${u.id}">1</td>
        <td th:text="${u.name}">张三</td>
    </tr>
</table>
<p th:if="${#lists.isEmpty(users)}">暂无用户</p>
</body>
</html>

<td> 里的静态文本是「原型占位」,浏览器直接打开时能看到示例内容,交给 Thymeleaf 渲染时则被真实数据替换。

进阶语法速览

  • 片段复用:th:fragment 定义公共片段,th:replace/th:insert 引入(布局、页头页脚常用);
  • 国际化:messages.properties 配合 #{key} 消息表达式;
  • 原始输出:th:utext 不转义直接输出 HTML,用户可控内容禁用,否则有 XSS 风险。

以上完整语法以 Thymeleaf 官方文档为准。

小结

Thymeleaf 的套路是:@Controller 返回视图名 + Model 传数据,模板里用 th:* 属性渲染。静态资源(10 章)配合模板(本章),就能做出完整的前后端同源页面应用。

笔记加载中…