好的,这里给你整理一份 Thymeleaf 简介,包含概念、特点、使用场景以及基础示例。
一、Thymeleaf 简介
Thymeleaf 是一个现代的 Java 模板引擎,用于在 Web 应用中生成 HTML、XML、JavaScript、CSS 等内容。它通常与 Spring Boot/Spring MVC 一起使用,替代传统的 JSP 模板。
核心特点
- 自然模板(Natural Templates)
- Thymeleaf 模板在浏览器中也能正常显示,便于前后端分离开发和设计师预览页面。
- 不会因为缺少数据而导致 HTML 页面无法渲染。
- 与 Spring 集成良好
- 提供 Spring MVC 支持,可以直接绑定模型数据(Model)到模板。
- 支持表达式语言(OGNL/SpEL),如
${user.name}
获取变量值。
- 丰富的功能
- 条件判断:
th:if
、th:unless
- 循环遍历:
th:each
- 属性绑定:
th:href
、th:src
、th:value
- URL 构建:
@{/path}
- 国际化支持:
#{message.key}
- 条件判断:
- 安全和扩展性
- 支持 HTML 转义,防止 XSS 攻击
- 可以通过自定义方言(Dialect)扩展功能
二、Thymeleaf 与 JSP 的区别
特性 | JSP | Thymeleaf |
---|---|---|
自然模板 | 否 | 是 |
与 Spring 集成 | 支持,但需要额外配置 | 与 Spring Boot 无缝集成 |
表达式语法 | ${} 或 <%= %> | ${} (OGNL/SpEL) |
HTML 预览 | 不能独立预览 | 可以在浏览器中预览 |
可维护性 | 中等 | 高 |
三、Thymeleaf 使用方法
1. 添加依赖(Spring Boot 示例)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 创建模板文件
目录结构:
src/main/resources/templates/
└── index.html
index.html 示例:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf 示例</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'">Hello, World!</h1>
<ul>
<li th:each="item : ${items}" th:text="${item}">Item</li>
</ul>
<a th:href="@{/about}">关于我们</a>
</body>
</html>
3. 创建 Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Arrays;
import java.util.List;
@Controller
public class HomeController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "Alice");
List<String> items = Arrays.asList("苹果", "香蕉", "橙子");
model.addAttribute("items", items);
return "index"; // 对应 templates/index.html
}
}
4. 启动 Spring Boot 应用
访问 http://localhost:8080/
即可看到 Thymeleaf 渲染的 HTML 页面。
四、Thymeleaf 常用语法
功能 | 语法示例 |
---|---|
输出变量 | th:text="${name}" |
条件判断 | th:if="${age > 18}" |
循环遍历 | th:each="item : ${items}" |
URL 构建 | th:href="@{/path}" |
表单绑定 | th:value="${user.name}" |
国际化 | th:text="#{message.key}" |
五、使用场景
- Spring MVC / Spring Boot Web 应用
- 用于渲染动态 HTML 页面
- 前后端分离的模板预览
- 设计师可以直接预览模板,不依赖后台数据
- 快速生成邮件模板或文档
- 通过 Thymeleaf 模板生成 HTML 邮件内容
六、总结
- Thymeleaf 是现代 Java Web 应用首选模板引擎,替代 JSP,更易维护。
- 优势:自然模板、与 Spring 无缝集成、语法简洁、可扩展性强。
- 开发技巧:熟练使用
th:text
、th:each
、th:if
,结合 Spring Model 数据即可快速构建动态页面。
发表回复