Thymeleaf 概述
Thymeleaf 是一款基于 Java 的现代化 HTML 模板引擎,被 Spring Boot 官方推荐作为 JSP 的替代方案。其核心优势在于支持 双模渲染:
- 静态模式:直接通过浏览器打开 HTML 文件时,Thymeleaf 标签属性会被忽略,显示原始静态内容。
- 动态模式:在服务器运行时,Thymeleaf 自动替换标签属性为动态数据,生成最终页面。
核心语法分类
表达式
${...}
:变量表达式,直接获取变量值。*{...}
:选择表达式,配合th:object
使用,简化对象属性访问。#{...}
:国际化消息表达式,用于文本国际化。@{...}
:URL 表达式,自动处理上下文路径。#maps
:内置对象操作工具(如日期、集合等)。
常用标签
- 数据绑定:
th:text
(文本渲染)、th:value
(表单值)、th:field
(表单字段绑定)。 - 流程控制:
th:if
(条件判断)、th:each
(循环遍历)。 - 资源处理:
th:href
(链接动态生成)、th:src
(资源路径动态化)。 - 模板复用:
th:fragment
(定义可复用片段)、th:include
(引入片段)。
内置工具函数
- 数据处理:
#dates.format()
(日期格式化)、#lists.isEmpty()
(集合判空)。 - 字符串操作:
#strings.substring()
(截取字符串)、#arrays.length()
(数组长度)。 - 数值处理:
#numbers.formatDecimal()
(数字格式化)。
官方资源
详细语法和高级功能可参考 Thymeleaf 官网文档。其模块化设计和自然模板特性使其成为前后端协作的高效工具。
配置和集成 Thymeleaf
在项目的 pom.xml
文件中添加 Thymeleaf 的 Starter 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
调整 Thymeleaf 配置
在 application.yml
文件中配置 Thymeleaf 的缓存选项,开发阶段建议关闭缓存:
spring:
thymeleaf:
cache: false
其他配置项可保持默认,具体默认配置可参考 ThymeleafProperties.java
类。
创建控制器
新建控制器类 UserController.java
,处理用户相关请求:
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/all")
public String all(Model model) {
model.addAttribute("users", userService.findAll());
return "all";
}
}
@Controller
标记该类为控制器,@RequestMapping
定义请求路径,Model
用于传递数据到前端。
创建 HTML 模板
在 resources/templates
目录下创建 all.html
文件:
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Thymeleaf</title>
</head>
<body>
<table>
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
<tr th:each="user:${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
</body>
</html>
引入 Thymeleaf 的命名空间后,可以使用 th:
前缀的标签进行数据绑定和循环操作。
启动应用并访问
启动 Spring Boot 主类后,在浏览器中输入以下地址访问接口:
http://localhost:8080/user/all