https://example.com/thymeleaf-spring-demo
前言
在前后端不分离的传统Web项目中,Thymeleaf凭借自然的HTML语法与强大的表达式功能成为Spring Boot官方推荐的模板引擎。本文将带你从零实现用户注册功能,涵盖表单验证、页面碎片化、国际化等核心场景,并分享性能调优实战经验。
一、快速整合Thymeleaf
1.1 添加基础依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.2 配置参数优化
yaml
# application.yml
spring:
thymeleaf:
cache: false # 开发阶段关闭缓存
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
二、Thymeleaf基础语法精讲
2.1 表达式类型速查
表达式 | 示例 | 说明 |
---|---|---|
${...} | ${user.name} | 变量表达式 |
*{...} | *{age} (需配合th:object使用) | 对象属性表达式 |
#{...} | #{login.title} | 国际化消息 |
@{...} | @{/user/register} | URL链接表达式 |
~{...} | ~{footer :: copyright} | 片段引用表达式 |
2.2 常用属性指令
html
<!-- 动态绑定属性 -->
<input th:value="${user.email}"
th:attr="data-id=${user.id}">
<!-- 条件渲染 -->
<div th:if="${#lists.isEmpty(users)}">
暂无数据
</div>
<!-- 循环遍历 -->
<ul th:each="item : ${items}">
<li th:text="${item.name}"></li>
</ul>
<!-- 表单绑定 -->
<form th:object="${user}" th:action="@{/save}">
<input th:field="*{username}">
</form>
三、用户注册功能实战
3.1 实体类与表单验证
java
@Data // Lombok
public class UserDTO {
@NotBlank(message = "用户名不能为空")
@Size(min = 4, max = 20)
private String username;
@Email(message = "邮箱格式错误")
private String email;
@Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$",
message = "密码至少8位,包含字母和数字")
private String password;
}
3.2 Controller层实现
java
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/register")
public String showForm(Model model) {
model.addAttribute("user", new UserDTO());
return "register";
}
@PostMapping("/save")
public String submitForm(@Valid @ModelAttribute("user") UserDTO user,
BindingResult result) {
if (result.hasErrors()) {
return "register"; // 返回表单页显示错误
}
// 保存用户逻辑
return "redirect:/success";
}
}
3.3 页面实现(register.html)
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{register.title}">用户注册</title>
</head>
<body>
<h2>用户注册</h2>
<form th:action="@{/user/save}" th:object="${user}" method="post">
<!-- 用户名输入 -->
<div>
<label>用户名:</label>
<input type="text" th:field="*{username}">
<span th:if="${#fields.hasErrors('username')}"
th:errors="*{username}" style="color:red"></span>
</div>
<!-- 其他字段类似 -->
<button type="submit">提交</button>
</form>
</body>
</html>
四、进阶功能实现
4.1 页面布局模板
定义基础模板(layouts/base.html):
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">默认标题</title>
<!-- 公共CSS/JS -->
</head>
<body>
<header th:replace="~{fragments/header :: main}"></header>
<div layout:fragment="content"></div>
<footer th:replace="~{fragments/footer :: main}"></footer>
</body>
</html>
子页面继承:
html
<html layout:decorate="~{layouts/base}"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>用户注册</title>
</head>
<body>
<div layout:fragment="content">
<!-- 页面具体内容 -->
</div>
</body>
</html>
4.2 国际化支持
messages.properties:
properties
register.title=User Registration
login.title=Sign In
页面使用:
html
<h1 th:text="#{register.title}"></h1>
切换语言:
java
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
五、性能优化与安全
5.1 缓存与压缩配置
yaml
spring:
thymeleaf:
cache: true # 生产环境开启
servlet:
content-type: text/html
compression-enabled: true # 启用GZIP压缩
5.2 防止XSS攻击
自动转义HTML:
html
<div th:text="${dangerString}"></div> <!-- 默认转义 -->
<div th:utext="${trustedHtml}"></div> <!-- 信任内容需手动标记 -->
5.3 静态资源处理
java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
六、实战挑战
-
动态表格渲染
实现分页显示用户列表,支持排序与搜索 -
文件上传集成
在注册页面添加头像上传功能,保存到MinIO -
AJAX表单提交
使用Fetch API异步提交表单,处理错误提示
挑战奖励:完成任意两项任务并截图到评论区,可获得《Thymeleaf高阶技巧》电子手册!
配套资源
上篇回顾:Spring Boot自动配置原理深度解析:揭开@SpringBootApplication的魔法面纱-优快云博客
下篇预告:《Spring Boot DevTools热部署:开发效率提升100%》——实时预览修改无需重启,明天见!
通过本文你已掌握:
- Thymeleaf与Spring Boot深度整合 ✅
- 表单验证与错误处理标准化流程 ✅
- 页面模块化与国际化方案 ✅
- 生产环境性能优化策略 ✅
思考题:如何在Thymeleaf中实现动态权限控制的菜单渲染?欢迎分享你的实现思路!