10、《Thymeleaf模板引擎:动态页面开发全攻略》
Thymeleaf模板引擎:动态页面开发全攻略
一、Thymeleaf核心价值解析
天然HTML亲和力:Thymeleaf允许直接使用.html
文件作为模板,支持浏览器直接预览静态原型,同时通过属性标签(如th:text
)实现动态渲染,完美实现「动静结合」开发模式。
Spring生态深度整合:与Spring Boot无缝对接,自动配置模板解析器、消息源等组件,通过spring-boot-starter-thymeleaf
依赖快速集成。
核心优势对比:
- 相比JSP:无需编译成Servlet,支持热更新
- 相比Freemarker:更简洁的表达式语法,更强的布局管理能力
二、Spring Boot整合实战
1. 基础环境搭建
<!-- pom.xml 关键依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
// 配置示例(application.yml)
spring:
thymeleaf:
cache: false # 开发关闭缓存
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
mode: HTML
2. 基础数据渲染
// Controller示例
@Controller
public class UserController {
@GetMapping("/users")
public String userList(Model model) {
List<User> users = userService.findAll();
model.addAttribute("users", users);
model.addAttribute("currentTime", LocalDateTime.now());
return "user/list";
}
}
<!-- templates/user/list.html -->
<table>
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>注册时间</th>
</tr>
</thead>
<tbody>
<!-- 循环渲染 -->
<tr th:each="user : ${users}">
<td th:text="${user.id}">1</td>
<td th:text="${user.username}">示例用户</td>
<!-- 日期格式化 -->
<td th:text="${#dates.format(user.createTime, 'yyyy-MM-dd HH:mm')}"></td>
</tr>
</tbody>
</table>
三、高级模板布局方案
1. 片段化布局(Fragment)
<!-- 定义公共头部 -->
<header th:fragment="commonHeader">
<nav>
<a th:href="@{/}">首页</a>
<a th:href="@{/users}">用户管理</a>
</nav>
</header>
<!-- 页面引用 -->
<div th:replace="~{fragments/header :: commonHeader}"></div>
2. 参数化布局继承
<!-- layout/base.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${pageTitle}">默认标题</title>
<th:block th:replace="~{fragments/css :: core}"></th:block>
</head>
<body>
<div th:replace="~{fragments/header}"></div>
<!-- 内容占位区 -->
<div th:insert="${content}"></div>
<div th:replace="~{fragments/footer}"></div>
</body>
</html>
<!-- 子页面继承 -->
<html th:replace="~{layout/base :: layout(
pageTitle='用户列表',
content=~{:: #mainContent}
)}">
<body>
<div id="mainContent">
<!-- 页面具体内容 -->
<table>...</table>
</div>
</body>
</html>
四、国际化(i18n)深度实践
1. 多语言资源配置
# messages.properties
welcome.message=Welcome!
user.list.title=User Management
# messages_zh_CN.properties
welcome.message=欢迎!
user.list.title=用户管理系统
2. 动态语言切换
// 语言切换控制器
@Controller
public class LocaleController {
@GetMapping("/changeLang")
public String changeLocale(@RequestParam String lang,
HttpServletRequest request) {
LocaleResolver localeResolver = RequestContextUtils
.getLocaleResolver(request);
localeResolver.setLocale(request, response, new Locale(lang));
return "redirect:" + request.getHeader("Referer");
}
}
<!-- 语言切换器 -->
<div class="lang-switcher">
<a th:href="@{/changeLang(lang='en')}">English</a>
<a th:href="@{/changeLang(lang='zh_CN')}">中文</a>
</div>
<!-- 国际化文本使用 -->
<h1 th:text="#{user.list.title}"></h1>
<p th:text="#{welcome.message(${#authentication.name})}"></p>
五、企业级开发技巧
1. 工具类方法扩展
// 自定义工具类
public class ThymeleafUtils {
public static String maskPhone(String phone) {
return phone.substring(0,3) + "****" + phone.substring(7);
}
}
// 模板中调用
<td th:text="${@thymeleafUtils.maskPhone(user.phone)}"></td>
2. 安全防护实践
<!-- 自动HTML转义 -->
<div th:text="${userInput}"></div>
<!-- 禁用转义(慎用) -->
<div th:utext="${trustedHtml}"></div>
<!-- 防御XSS最佳实践 -->
<script th:inline="javascript">
var userId = [[${user.id}]];
var userName = /*[[${#strings.escapeJavaScript(user.name)}]]*/ "";
</script>
结语
Thymeleaf通过优雅的HTML原生模板设计,配合强大的Spring生态整合能力,已成为现代Java Web开发的优选方案。本文从基础整合到企业级应用场景,覆盖了服务端渲染、布局管理和国际化等核心功能。建议开发者在实际项目中注意:
- 模板目录结构的规范化管理
- 复杂业务逻辑应避免在模板中实现
- 结合Spring Security进行细粒度权限控制
- 使用Fragment缓存提升性能