Spring Boot实战:5分钟搞定Thymeleaf静态资源与动态数据绑定
刚接触Spring Boot的开发者,在构建第一个Web应用时,往往会遇到两个让人头疼的问题:静态资源加载不出来,页面上显示一堆404错误;或者明明Controller里传了数据,但页面上就是看不到。这两个问题看似简单,却能让新手在起步阶段就卡住很久。
我刚开始用Spring Boot时,也在这两个坑里挣扎过。记得有一次,我花了一个多小时调试一个CSS文件为什么加载不了,最后发现只是路径写错了一个斜杠。还有一次,我写了个用户登录页面,后端数据明明传过去了,前端却始终显示默认值,后来才发现是Thymeleaf的命名空间声明漏掉了。
今天,我就通过一个完整的用户登录页面案例,带你快速掌握Thymeleaf的核心用法。我会重点解决新手最常遇到的“静态资源加载404”和“模板解析失败”问题,并分享一些IntelliJ IDEA中的实用调试技巧。读完这篇文章,你不仅能快速上手Thymeleaf,还能避开那些常见的坑。
1. 环境准备与项目创建
1.1 快速创建Spring Boot项目
使用IntelliJ IDEA创建Spring Boot项目是最快捷的方式。打开IDEA,选择“File” → “New” → “Project”,然后选择“Spring Initializr”。这里有个小技巧:如果你网络环境不太好,可以尝试切换不同的服务URL,比如使用阿里云的镜像源https://start.aliyun.com,这样项目创建速度会快很多。
在依赖选择界面,确保勾选以下两个核心依赖:
- Spring Web - 提供Web MVC支持
- Thymeleaf - 模板引擎
如果你已经创建了项目但忘记添加依赖,可以直接在pom.xml中添加:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
1.2 项目结构解析
创建完成后,你的项目结构应该类似这样:
src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── demo/
│ │ ├── DemoApplication.java
│ │ └── controller/
│ │ └── LoginController.java
│ └── resources/
│ ├── static/
│ │ ├── css/
│ │ │ └── style.css
│ │ └── js/
│ │ └── login.js
│ ├── templates/
│ │ └── login.html
│ └── application.properties
└── test/
这里需要特别注意几个关键目录:
static/- 存放所有静态资源(CSS、JavaScript、图片等)templates/- 存放Thymeleaf模板文件(HTML)application.properties- 项目配置文件
注意:Spring Boot默认的静态资源路径是
/static、/public、/resources和/META-INF/resources。通常我们使用/static目录,因为它最直观。
1.3 基础配置调整
在application.properties中添加一些基础配置,这些配置不是必须的,但能让开发过程更顺畅:
# 开发时关闭模板缓存,修改后立即生效
spring.thymeleaf.cache=false
# 设置字符编码
spring.thymeleaf.encoding=UTF-8
# 模板模式(HTML5)
spring.thymeleaf.mode=HTML
# 模板文件前缀和后缀
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 静态资源路径(默认就是这个,显式声明更清晰)
spring.web.resources.static-locations=classpath:/static/
如果你发现HTML标签必须严格闭合(比如<meta>标签必须写成<meta />),可以调整为宽松模式:
spring.thymeleaf.mode=LEGACYHTML5
但使用LEGACYHTML5模式需要额外添加依赖:
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
2. 静态资源处理:告别404错误
2.1 静态资源的正确存放位置
新手最容易犯的错误就是把静态资源放错位置。Spring Boot有明确的静态资源查找顺序,我整理了一个表格来说明:
| 目录 | 优先级 | 说明 |
|---|---|---|
classpath:/META-INF/resources/ | 1 | 通常用于存放库自带的资源 |
classpath:/resources/ | 2 | 项目根目录下的resources文件夹 |
classpath:/static/ | 3 | 最常用,我们主要用这个 |
classpath:/public/ | 4 | 公共资源 |
在实际开发中,我建议统一使用/static目录,这样结构清晰,不容易混乱。在这个目录下,可以进一步按类型组织:
static/
├── css/
│ ├── bootstrap.min.css
│ └── custom.css
├── js/
│ ├── jquery.min.js
│ └── app.js
├── images/
│ ├── logo.png
│ └── background.jpg
└── fonts/
└── fontawesome.woff2
2.2 Thymeleaf中引用静态资源
在Thymeleaf模板中引用静态资源,必须使用Thymeleaf的链接表达式语法@{...}。这是很多新手会忽略的关键点。
错误示例(会导致404):
<link rel="stylesheet" href="/css/style.css">
<script src="/js/login.js"></script>
<img src="/images/logo.png">
正确示例:
<link rel="stylesheet" th:href="@{/css/style.css}">
<script th:src="@{/js/login.js}"></script>
<img th:src="@{/images/logo.png}">
注意这里的路径写法:@{/css/style.css}。开头的斜杠/表示从应用上下文根目录开始。如果你的应用部署在http://localhost:8080/myapp,那么@{/css/style.css}会被解析为/myapp/css/style.css。
2.3 静态资源加载的调试技巧
当静态资源加载失败时,可以按以下步骤排查:
-
检查控制台输出:启动应用时,Spring Boot会输出静态资源映射信息:
Mapped URL path [/webjars/**] onto handler... Mapped URL path [/**] onto handler... -
直接访问资源:在浏览器中直接输入URL,比如
http://localhost:8080/css/style.css。如果能访问,说明资源路径正确;如果不能,说明资源不存在或路径错误。 -
使用IDEA的路径提示:在Thymeleaf模板中,当输入
@{/时,IDEA会智能提示static目录下的资源:<!-- 输入 @{/ 后,IDEA会显示可用资源 --> <link rel="stylesheet" th:href="@{/css/}"> <!-- 这里会提示style.css --> -
查看网络请求:按F12打开开发者工具,查看Network标签页。如果资源请求返回404,检查请求的URL是否正确。
2.4 常见问题与解决方案
我整理了几个最常见的静态资源问题及其解决方案:
| 问题现象 | 可能原因 | 解决方案 |
|---|---|---|
| CSS/JS文件加载404 | 1. 文件不在static目录下2. Thymeleaf语法错误(没用 @{})3. 路径前缺少 / | 1. 检查文件位置 2. 使用 th:href="@{/path}"3. 确保路径以 /开头 |
| 图片不显示 | 1. 文件名大小写不一致 2. 文件扩展名错误 3. 浏览器缓存 | 1. 统一使用小写文件名 2. 检查图片格式 3. Ctrl+F5强制刷新 |
| 字体文件404 | 1. 字体文件被安全策略拦截 2. MIME类型不正确 | 1. 配置CORS 2. 添加MIME类型映射 |
提示:在开发阶段,我习惯在Chrome开发者工具的Network面板中勾选“Disable cache”,这样可以避免浏览器缓存导致的资源更新不及时问题。
3. 用户登录页面实战开发
3.1 创建登录页面模板
在templates目录下创建login.html,这是一个完整的用户登录页面示例:
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户登录 - 我的应用</title>
<!-- 引入Bootstrap CSS -->
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<!-- 引入自定义CSS -->
<link rel="stylesheet" th:href="@{/css/login.css}">
<!-- 引入Font Awesome图标 -->
<link rel="stylesheet" th:href="@{https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css}">
</head>
<body>
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-6 col-lg-4">
<div class="card shadow-sm">
<div class="card-header bg-primary text-white text-center">
<h4 class="mb-0">
<i class="fas fa-sign-in-alt me-2"></i>用户登录
</h4>
</div>
<div class="card-body">
<!-- 显示错误消息(动态数据) -->
<div th:if="${errorMessage}" class="alert alert-danger alert-dismissible fade show" role="alert">
<i class="fas fa-exclamation-circle me-2"></i>
<span th:text="${errorMessage}">错误消息占位符</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<!-- 显示成功消息 -->
<div th:if="${successMessage}" class="alert alert-success alert-dismissible fade show" role="alert">
<i class="fas fa-check-circle me-2"></i>
<span th:text="${successMessage}">成功消息占位符</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<!-- 登录表单 -->
<form th:action="@{/login}" method="post" th:object="${loginForm}">
<div class="mb-3">
<label for="username" class="form-label">
<i class="fas fa-user me-2"></i>用户名
</label>
<input type="text"
class="form-control"
id="username"
th:field="*{username}"
placeholder="请输入用户名"
required>
<div class="form-text">请输入您的用户名或邮箱</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">
<i class="fas fa-lock me-2"></i>密码
</label>
<input type="password"
class="form-control"
id="password"
th:field="*{password}"
placeholder="请输入密码"
required>
<div class="form-text">密码长度至少6位</div>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="rememberMe">
<label class="form-check-label" for="rememberMe">记住我</label>
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary">
<i class="fas fa-sign-in-alt me-2"></i>登录
</button>
<a th:href="@{/register}" class="btn btn-outline-secondary">
<i class="fas fa-user-plus me-2"></i>注册新账户
</a>
</div>
</form>
<hr class="my-4">
<div class="text-center">
<small class="text-muted">
<i class="fas fa-info-circle me-1"></i>
首次登录?<a th:href="@{/forgot-password}">忘记密码</a>
</small>
</div>
</div>
<div class="card-footer text-center text-muted">
<small>
© 2024 我的应用.
<span th:text="${currentYear}">2024</span> 版权所有
</small>
</div>
</div>
<!-- 页面访问统计(演示复杂表达式) -->
<div class="text-center mt-3">
<small class="text-muted">
本页面已被访问
<span th:text="${visitCount != null ? visitCount : 0}">0</span> 次
<span th:if="${visitCount != null and visitCount > 100}">
(热门页面!)
</span>
</small>
</div>
</div>
</div>
</div>
<!-- 引入Bootstrap JS -->
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
<!-- 引入自定义JS -->
<script th:src="@{/js/login.js}"></script>
<!-- 内联JavaScript(演示th:inline) -->
<script th:inline="javascript">
/*<![CDATA[*/
document.addEventListener('DOMContentLoaded', function() {
// 从Thymeleaf获取数据
const errorMsg = /*[[${errorMessage}]]*/ null;
const successMsg = /*[[${successMessage}]]*/ null;
if (errorMsg) {
console.error('登录错误:', errorMsg);
}
if (successMsg) {
console.log('操作成功:', successMsg);
}
// 自动聚焦到用户名输入框
const usernameInput = document.getElementById('username');
if (usernameInput && !usernameInput.value) {
usernameInput.focus();
}
});
/*]]>*/
</script>
</body>
</html>
这个模板展示了Thymeleaf的几个关键特性:
- 命名空间声明:
xmlns:th="http://www.thymeleaf.org"必须加在<html>标签上 - 静态资源引用:使用
th:href="@{/path}"和th:src="@{/path}" - 条件显示:
th:if用于根据条件显示/隐藏元素 - 表单绑定:
th:object和th:field用于表单数据绑定 - 表达式求值:
th:text用于显示动态文本
3.2 创建对应的CSS和JavaScript文件
在static/css/login.css中:
/* 登录页面自定义样式 */
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
}
.card {
border: none;
border-radius: 15px;
overflow: hidden;
}
.card-header {
border-radius: 15px 15px 0 0 !important;
padding: 1.5rem;
}
.card-body {
padding: 2rem;
}
.form-control {
border-radius: 8px;
padding: 0.75rem 1rem;
border: 1px solid #dee2e6;
transition: all 0.3s;
}
.form-control:focus {
border-color: #667eea;
box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
}
.btn {
border-radius: 8px;
padding: 0.75rem;
font-weight: 500;
transition: all 0.3s;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}
.alert {
border-radius: 8px;
border: none;
}
/* 响应式调整 */
@media (max-width: 768px) {
.container {
padding: 1rem;
}
.card-body {
padding: 1.5rem;
}
}
在static/js/login.js中:
// 登录页面交互逻辑
document.addEventListener('DOMContentLoaded', function() {
// 表单提交前验证
const loginForm = document.querySelector('form');
if (loginForm) {
loginForm.addEventListener('submit', function(event) {
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
// 简单的前端验证
if (!username) {
showError('请输入用户名');
event.preventDefault();
return;
}
if (!password) {
showError('请输入密码');
event.preventDefault();
return;
}
if (password.length < 6) {
showError('密码长度至少6位');
event.preventDefault();
return;
}
// 显示加载状态
const submitBtn = loginForm.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>登录中...';
submitBtn.disabled = true;
// 3秒后恢复(防止重复提交)
setTimeout(() => {
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
}, 3000);
});
}
// 显示错误提示
function showError(message) {
// 如果已经有错误提示,先移除
const existingAlert = document.querySelector('.alert-danger');
if (existingAlert) {
existingAlert.remove();
}
// 创建新的错误提示
const alertDiv = document.createElement('div');
alertDiv.className = 'alert alert-danger alert-dismissible fade show';
alertDiv.innerHTML = `
<i class="fas fa-exclamation-circle me-2"></i>
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
`;
// 插入到表单前面
const form = document.querySelector('form');
if (form) {
form.parentNode.insertBefore(alertDiv, form);
// 5秒后自动消失
setTimeout(() => {
if (alertDiv.parentNode) {
const bsAlert = new bootstrap.Alert(alertDiv);
bsAlert.close();
}
}, 5000);
}
}
// 密码显示/隐藏切换
const togglePassword = document.createElement('button');
togglePassword.type = 'button';
togglePassword.className = 'btn btn-outline-secondary btn-sm position-absolute';
togglePassword.style.right = '10px';
togglePassword.style.top = '50%';
togglePassword.style.transform = 'translateY(-50%)';
togglePassword.innerHTML = '<i class="fas fa-eye"></i>';
const passwordInput = document.getElementById('password');
if (passwordInput) {
passwordInput.parentNode.style.position = 'relative';
passwordInput.parentNode.appendChild(togglePassword);
togglePassword.addEventListener('click', function() {
const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
passwordInput.setAttribute('type', type);
this.innerHTML = type === 'password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>';
});
}
});
3.3 创建Controller处理登录逻辑
在controller包下创建LoginController.java:
package com.example.demo.controller;
import com.example.demo.model.LoginForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Controller
public class LoginController {
// 模拟用户数据库
private static final Map<String, String> USER_DATABASE = new HashMap<>();
private static final AtomicInteger VISIT_COUNT = new AtomicInteger(0);
static {
// 初始化测试用户
USER_DATABASE.put("admin", "admin123");
USER_DATABASE.put("user", "user123");
USER_DATABASE.put("test", "test123");
}
/**
* 显示登录页面
*/
@GetMapping("/login")
public String showLoginPage(Model model,
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
// 访问计数
int count = VISIT_COUNT.incrementAndGet();
// 添加模型属性
model.addAttribute("currentYear", Year.now().getValue());
model.addAttribute("visitCount", count);
model.addAttribute("loginForm", new LoginForm());
model.addAttribute("pageTitle", "用户登录");
model.addAttribute("currentTime", LocalDateTime.now());
// 处理错误和退出消息
if (error != null) {
model.addAttribute("errorMessage", "用户名或密码错误!");
}
if (logout != null) {
model.addAttribute("successMessage", "您已成功退出登录!");
}
// 模拟一些额外的数据用于演示
model.addAttribute("serverInfo", Map.of(
"name", "开发服务器",
"version", "1.0.0",
"environment", "开发环境"
));
return "login";
}
/**
* 处理登录请求
*/
@PostMapping("/login")
public String processLogin(@ModelAttribute LoginForm loginForm,
Model model) {
String username = loginForm.getUsername();
String password = loginForm.getPassword();
// 简单的验证逻辑
if (username == null || username.trim().isEmpty()) {
model.addAttribute("errorMessage", "用户名不能为空!");
model.addAttribute("loginForm", loginForm);
return "login";
}
if (password == null || password.trim().isEmpty()) {
model.addAttribute("errorMessage", "密码不能为空!");
model.addAttribute("loginForm", loginForm);
return "login";
}
// 检查用户是否存在
if (!USER_DATABASE.containsKey(username)) {
model.addAttribute("errorMessage", "用户不存在!");
model.addAttribute("loginForm", loginForm);
return "login";
}
// 验证密码
if (!USER_DATABASE.get(username).equals(password)) {
model.addAttribute("errorMessage", "密码错误!");
model.addAttribute("loginForm", loginForm);
return "login";
}
// 登录成功
model.addAttribute("successMessage", "登录成功!欢迎回来," + username + "!");
model.addAttribute("username", username);
model.addAttribute("loginTime", LocalDateTime.now());
// 这里应该重定向到主页,但为了演示,我们仍然返回登录页面
return "redirect:/dashboard?username=" + username;
}
/**
* 显示注册页面
*/
@GetMapping("/register")
public String showRegisterPage(Model model) {
model.addAttribute("currentYear", Year.now().getValue());
return "register";
}
/**
* 显示忘记密码页面
*/
@GetMapping("/forgot-password")
public String showForgotPasswordPage(Model model) {
model.addAttribute("currentYear", Year.now().getValue());
return "forgot-password";
}
/**
* 模拟仪表板页面
*/
@GetMapping("/dashboard")
public String showDashboard(@RequestParam String username, Model model) {
model.addAttribute("username", username);
model.addAttribute("welcomeMessage", "欢迎进入系统控制面板");
model.addAttribute("loginTime", LocalDateTime.now());
model.addAttribute("userRole", "管理员");
// 模拟一些统计数据
model.addAttribute("stats", Map.of(
"totalUsers", 156,
"activeSessions", 23,
"todayVisits", 89,
"systemLoad", "42%"
));
return "dashboard";
}
}
3.4 创建数据模型
在model包下创建LoginForm.java:
package com.example.demo.model;
public class LoginForm {
private String username;
private String password;
// 构造器
public LoginForm() {
}
public LoginForm(String username, String password) {
this.username = username;
this.password = password;
}
// Getter和Setter
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// toString方法(调试用)
@Override
public String toString() {
return "LoginForm{" +
"username='" + username + '\'' +
", password='[PROTECTED]'" +
'}';
}
}
4. Thymeleaf数据绑定深度解析
4.1 变量表达式:${...}
这是Thymeleaf中最常用的表达式,用于访问模型中的数据。支持多种数据类型:
<!-- 简单字符串 -->
<p th:text="${message}">默认消息</p>
<!-- 对象属性 -->
<p th:text="${user.name}">用户名</p>
<p th:text="${user['email']}">邮箱</p>
<p th:text="${user.getAge()}">年龄</p>
<!-- 表达式运算 -->
<p th:text="${price * quantity}">总价</p>
<p th:text="${discount > 0 ? '有折扣' : '无折扣'}">折扣状态</p>
4.2 选择变量表达式:*{...}
选择表达式通常与th:object一起使用,用于简化对象属性的访问:
<!-- 使用th:object指定对象 -->
<div th:object="${user}">
<!-- 在div内部,可以直接使用*{}访问对象属性 -->
<p>姓名: <span th:text="*{name}">默认姓名</span></p>
<p>邮箱: <span th:text="*{email}">默认邮箱</span></p>
<p>年龄: <span th:text="*{age}">默认年龄</span></p>
</div>
<!-- 等价于 -->
<div>
<p>姓名: <span th:text="${user.name}">默认姓名</span></p>
<p>邮箱: <span th:text="${user.email}">默认邮箱</span></p>
<p>年龄: <span th:text="${user.age}">默认年龄</span></p>
</div>
4.3 消息表达式:#{...}
用于国际化,从属性文件中读取消息:
# messages.properties
login.title=用户登录
login.username=用户名
login.password=密码
login.submit=登录
login.error=登录失败,请重试
<h1 th:text="#{login.title}">Login</h1>
<label th:text="#{login.username}">Username</label>
<button th:text="#{login.submit}">Submit</button>
4.4 链接表达式:@{...}
专门用于处理URL,支持绝对路径、相对路径和带参数的URL:
<!-- 绝对路径 -->
<a th:href="@{https://www.example.com}">外部链接</a>
<!-- 相对路径(相对于上下文根) -->
<a th:href="@{/login}">登录页面</a>
<!-- 带路径变量 -->
<a th:href="@{/users/{id}/profile(id=${userId})}">用户资料</a>
<!-- 带查询参数 -->
<a th:href="@{/search(page=${currentPage}, size=${pageSize})}">搜索</a>
<!-- 多个参数 -->
<a th:href="@{/api/data(id=${id}, type=${type}, format='json')}">获取数据</a>
4.5 常用Thymeleaf属性
Thymeleaf通过HTML属性扩展功能,以下是一些最常用的属性:
| 属性 | 用途 | 示例 |
|---|---|---|
th:text | 设置文本内容 | <p th:text="${message}">默认文本</p> |
th:utext | 设置HTML内容(不转义) | <div th:utext="${htmlContent}"></div> |
th:value | 设置表单元素值 | <input th:value="${user.name}"> |
th:href | 设置链接地址 | <a th:href="@{/profile}">资料</a> |
th:src | 设置资源地址 | <img th:src="@{/images/logo.png}"> |
th:if | 条件显示 | <div th:if="${user != null}">欢迎</div> |
th:unless | 条件不显示 | <div th:unless="${user != null}">请登录</div> |
th:each | 循环遍历 | <tr th:each="item : ${items}"> |
th:switch/th:case | 多条件选择 | 见下文示例 |
th:object | 指定表单对象 | <form th:object="${user}"> |
th:field | 表单字段绑定 | <input th:field="*{username}"> |
th:attr | 设置任意属性 | <div th:attr="data-id=${id}"></div> |
th:classappend | 追加CSS类 | <div th:classappend="${isActive ? 'active' : ''}"> |
th:style | 设置内联样式 | <div th:style="'color:' + ${color}"> |
4.6 条件判断与循环
条件判断示例:
<!-- if/unless -->
<div th:if="${user.active}">
用户已激活
</div>
<div th:unless="${user.active}">
用户未激活
</div>
<!-- switch/case -->
<div th:switch="${user.role}">
<p th:case="'admin'">管理员用户</p>
<p th:case="'user'">普通用户</p>
<p th:case="'guest'">访客用户</p>
<p th:case="*">未知角色</p>
</div>
<!-- 复杂条件 -->
<div th:if="${user.age >= 18 and user.verified}">
成年已验证用户
</div>
<div th:if="${user.subscription == null or user.subscription.expired}">
需要订阅
</div>
循环遍历示例:
<!-- 基本循环 -->
<table>
<tr th:each="user : ${users}">
<td th:text="${user.name}">姓名</td>
<td th:text="${user.email}">邮箱</td>
</tr>
</table>
<!-- 循环状态变量 -->
<table>
<tr th:each="user, iterStat : ${users}">
<td th:text="${iterStat.index}">索引</td>
<td th:text="${iterStat.count}">计数</td>
<td th:text="${iterStat.size}">总数</td>
<td th:text="${iterStat.current.name}">当前用户</td>
<td th:text="${iterStat.even} ? '偶数行' : '奇数行'">奇偶</td>
<td th:text="${iterStat.first} ? '第一行' : ''">首行</td>
<td th:text="${iterStat.last} ? '最后一行' : ''">末行</td>
</tr>
</table>
<!-- 嵌套循环 -->
<div th:each="category : ${categories}">
<h3 th:text="${category.name}">分类</h3>
<ul>
<li th:each="product : ${category.products}"
th:text="${product.name}">产品</li>
</ul>
</div>
4.7 实用工具对象
Thymeleaf提供了一些内置工具对象,方便在模板中使用:
<!-- #dates:日期格式化 -->
<p th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}">生日</p>
<p th:text="${#dates.createNow()}">当前时间</p>
<p th:text="${#dates.dayOfWeekName(#dates.createNow())}">星期几</p>
<!-- #strings:字符串操作 -->
<p th:text="${#strings.toUpperCase(user.name)}">大写姓名</p>
<p th:text="${#strings.toLowerCase(user.email)}">小写邮箱</p>
<p th:text="${#strings.substring(message, 0, 100)}">摘要</p>
<p th:text="${#strings.length(description)}">长度</p>
<p th:text="${#strings.replace(text, 'old', 'new')}">替换</p>
<p th:if="${#strings.isEmpty(input)}">输入为空</p>
<!-- #numbers:数字格式化 -->
<p th:text="${#numbers.formatDecimal(price, 1, 2)}">价格</p>
<p th:text="${#numbers.formatInteger(count, 3)}">计数</p>
<p th:text="${#numbers.formatPercent(ratio, 1, 2)}">百分比</p>
<!-- #lists:列表操作 -->
<p th:text="${#lists.size(items)}">列表大小</p>
<p th:text="${#lists.isEmpty(list)} ? '空列表' : '非空列表'">列表状态</p>
<p th:if="${#lists.contains(permissions, 'admin')}">有管理员权限</p>
<!-- #maps:Map操作 -->
<p th:text="${#maps.size(userMap)}">用户数量</p>
<p th:if="${#maps.containsKey(config, 'featureEnabled')}">功能已启用</p>
<!-- #arrays:数组操作 -->
<p th:text="${#arrays.length(userArray)}">数组长度</p>
<!-- #sets:Set操作 -->
<p th:text="${#sets.size(uniqueTags)}">唯一标签数</p>
<!-- #aggregates:聚合操作 -->
<p th:text="${#aggregates.sum(order.amounts)}">总金额</p>
<p th:text="${#aggregates.avg(scores)}">平均分</p>
<!-- #ids:ID生成 -->
<div th:id="${#ids.next('section')}">分区1</div>
<div th:id="${#ids.next('section')}">分区2</div>
<!-- #calendars:日历操作(类似#dates) -->
<p th:text="${#calendars.format(calendar, 'yyyy/MM/dd')}">日历日期</p>
<!-- #temporals:Java 8时间API -->
<p th:text="${#temporals.format(localDate, 'yyyy-MM-dd')}">本地日期</p>
<p th:text="${#temporals.day(localDateTime)}">日</p>
<p th:text="${#temporals.month(localDateTime)}">月</p>
<p th:text="${#temporals.year(localDateTime)}">年</p>
5. IntelliJ IDEA高效开发技巧
5.1 Thymeleaf插件配置
IntelliJ IDEA对Thymeleaf有很好的支持,但需要正确配置:
-
确保插件已启用:
- 打开
File→Settings→Plugins - 搜索 "Thymeleaf",确保插件已启用
- 打开
-
配置Thymeleaf支持:
File→Settings→Languages & Frameworks→Thymeleaf- 勾选 "Enable Thymeleaf"
- 设置模板路径(默认已正确识别)
-
代码自动完成:
- 在HTML文件中输入
th:,IDEA会自动提示可用属性 - 输入
${或*{,IDEA会提示模型中的属性 - 输入
@{/,IDEA会提示静态资源
- 在HTML文件中输入
5.2 调试技巧
实时模板预览: IDEA支持Thymeleaf模板的实时预览。在模板文件上右键,选择 "Open in Browser" → "Choose Browser",但更实用的是使用内置预览:
- 打开Thymeleaf模板文件
- 点击编辑器右上角的浏览器图标
- 选择 "Preview" 或 "Debug Preview"
表达式求值调试: 当表达式不按预期工作时,可以在IDEA的调试模式下查看:
- 在Controller中设置断点
- 以Debug模式启动应用
- 访问页面触发断点
- 在 "Variables" 窗口中查看模型数据
快速导航:
Ctrl+B(Windows)或Cmd+B(Mac):从Thymeleaf表达式跳转到Controller中的变量定义Ctrl+Alt+B:从Controller跳转到对应的模板文件Ctrl+鼠标点击:直接跳转到定义
5.3 代码模板与快捷键
创建自定义代码模板可以大幅提高开发效率:
-
创建Thymeleaf片段模板:
File→Settings→Editor→Live Templates- 点击 "+" 添加新模板组 "Thymeleaf"
- 添加模板:
- Abbreviation:
thform - Template text:
<form th:action="@{/$ACTION$}" method="$METHOD$" th:object="${$OBJECT$}"> <div class="mb-3"> <label for="$ID$" class="form-label">$LABEL$</label> <input type="$TYPE$" class="form-control" id="$ID$" th:field="*{$FIELD$}" $END$> </div> </form> - 设置适用的上下文为 "HTML"
- Abbreviation:
-
常用快捷键:
Ctrl+Alt+L:格式化代码Ctrl+Shift+F10:运行当前应用Shift+F10:运行上次配置Ctrl+Shift+F:全局搜索Ctrl+Shift+R:全局替换Alt+Insert:生成代码(Getter/Setter等)
5.4 问题排查工具
查看Thymeleaf解析结果: 在开发过程中,有时需要查看Thymeleaf最终生成的HTML。可以通过以下方式:
-
在
application.properties中添加:logging.level.org.thymeleaf=DEBUG logging.level.org.thymeleaf.TemplateEngine=DEBUG -
在浏览器中查看页面源代码(不是元素检查)
使用开发者工具:
- Chrome开发者工具的 "Network" 标签:查看资源加载情况
- "Console" 标签:查看JavaScript错误
- "Elements" 标签:查看最终渲染的DOM结构
IDEA内置工具:
- "Run" 窗口:查看应用启动日志
- "Debug" 窗口:查看断点信息
- "Terminal" 窗口:执行Maven/Gradle命令
5.5 性能优化建议
开发阶段配置:
# 关闭缓存,修改模板立即生效
spring.thymeleaf.cache=false
# 关闭静态资源缓存
spring.web.resources.cache.period=0
# 详细错误信息
server.error.include-stacktrace=always
生产环境配置:
# 开启模板缓存
spring.thymeleaf.cache=true
# 静态资源缓存1年
spring.web.resources.cache.period=31536000
spring.web.resources.cache.cachecontrol.max-age=31536000
spring.web.resources.cache.cachecontrol.public=true
# 压缩静态资源
spring.web.resources.chain.compressed=true
spring.web.resources.chain.strategy.content.enabled=true
spring.web.resources.chain.strategy.content.paths=/**
# 只记录错误日志
logging.level.org.thymeleaf=ERROR
模板优化技巧:
- 避免深层嵌套:Thymeleaf处理深层嵌套结构时性能较差
- 使用片段(Fragment):将重复部分提取为片段
- 减少内联JavaScript:尽量使用外部JS文件
- 合理使用缓存:对于不常变化的数据,考虑在Controller层缓存
5.6 实际项目中的最佳实践
在我参与过的多个Spring Boot项目中,总结了一些Thymeleaf使用的最佳实践:
目录结构规范:
resources/
├── static/
│ ├── css/
│ │ ├── base/ # 基础样式
│ │ ├── components/ # 组件样式
│ │ ├── pages/ # 页面特定样式
│ │ └── vendors/ # 第三方库样式
│ ├── js/
│ │ ├── lib/ # 第三方库
│ │ ├── components/ # 可复用组件
│ │ ├── pages/ # 页面特定脚本
│ │ └── app.js # 应用入口
│ ├── images/
│ │ ├── icons/ # 图标
│ │ ├── logos/ # Logo
│ │ └── backgrounds/ # 背景图
│ └── fonts/ # 字体文件
├── templates/
│ ├── fragments/ # 模板片段
│ │ ├── header.html
│ │ ├── footer.html
│ │ ├── sidebar.html
│ │ └── modal.html
│ ├── layouts/ # 布局模板
│ │ ├── default.html
│ │ ├── admin.html
│ │ └── auth.html
│ ├── pages/ # 页面模板
│ │ ├── home/
│ │ ├── auth/
│ │ ├── user/
│ │ └── admin/
│ └── errors/ # 错误页面
│ ├── 404.html
│ └── 500.html
└── application.properties
模板片段示例(fragments/header.html):
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head(title, styles, scripts)">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title th:text="${title} + ' - 我的应用'">默认标题</title>
<!-- 基础CSS -->
<link rel="stylesheet" th:href="@{/css/vendors/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/css/base/variables.css}">
<link rel="stylesheet" th:href="@{/css/base/reset.css}">
<link rel="stylesheet" th:href="@{/css/base/typography.css}">
<link rel="stylesheet" th:href="@{/css/base/layout.css}">
<!-- 页面特定CSS -->
<th:block th:each="style : ${styles}">
<link rel="stylesheet" th:href="@{${style}}">
</th:block>
<!-- 基础JavaScript -->
<script th:src="@{/js/lib/jquery.min.js}" defer></script>
<script th:src="@{/js/lib/bootstrap.bundle.min.js}" defer></script>
<!-- 页面特定JavaScript -->
<th:block th:each="script : ${scripts}">
<script th:src="@{${script}}" defer></script>
</th:block>
<!-- 元标签 -->
<meta name="description" th:content="${description ?: '默认描述'}">
<meta name="keywords" th:content="${keywords ?: '默认关键词'}">
<meta name="author" content="我的应用">
<!-- Favicon -->
<link rel="icon" th:href="@{/images/favicon.ico}" type="image/x-icon">
<link rel="apple-touch-icon" th:href="@{/images/apple-touch-icon.png}">
</head>
布局模板示例(layouts/default.html):
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head th:replace="fragments/header :: head(
title=${pageTitle},
styles=${pageStyles ?: []},
scripts=${pageScripts ?: []}
)">
</head>
<body>
<!-- 导航栏 -->
<header th:replace="fragments/header :: navbar"></header>
<!-- 主要内容区域 -->
<main class="container-fluid" layout:fragment="content">
<div class="row">
<div class="col-12">
<h1>默认内容</h1>
<p>请使用 layout:fragment="content" 替换此内容</p>
</div>
</div>
</main>
<!-- 页脚 -->
<footer th:replace="fragments/footer :: footer"></footer>
<!-- 模态框容器 -->
<div th:replace="fragments/modal :: modal-container"></div>
<!-- 页面特定脚本 -->
<div layout:fragment="scripts"></div>
</body>
</html>
页面使用示例:
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layouts/default}">
<th:block layout:fragment="pageStyles">
<link rel="stylesheet" th:href="@{/css/pages/login.css}">
</th:block>
<th:block layout:fragment="pageScripts">
<script th:src="@{/js/pages/login.js}"></script>
</th:block>
<div layout:fragment="content">
<div class="login-container">
<h1 class="text-center mb-4" th:text="${pageTitle}">登录</h1>
<!-- 登录表单 -->
<form th:action="@{/login}" method="post" class="login-form">
<!-- 表单内容 -->
</form>
</div>
</div>
<th:block layout:fragment="scripts">
<script>
// 页面特定的JavaScript代码
$(document).ready(function() {
console.log('登录页面加载完成');
});
</script>
</th:block>
这种模块化的组织方式有几个明显优势:
- 代码复用:公共部分只需编写一次
- 易于维护:修改公共部分时,所有页面自动更新
- 结构清晰:每个文件职责单一
- 团队协作:不同开发者可以同时工作在不同模块
性能监控与优化: 在实际项目中,我通常会添加一些监控点来确保Thymeleaf的性能:
@ControllerAdvice
public class ThymeleafPerformanceAdvice {
private static final Logger logger = LoggerFactory.getLogger(ThymeleafPerformanceAdvice.class);
@ModelAttribute
public void addPerformanceAttributes(HttpServletRequest request, Model model) {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
}
@AfterCompletion
public void logPerformance(HandlerMethod handlerMethod, HttpServletRequest request) {
Long startTime = (Long) request.getAttribute("startTime");
if (startTime != null) {
long duration = System.currentTimeMillis() - startTime;
String viewName = handlerMethod.getMethod().getName();
if (duration > 100) { // 超过100ms记录警告
logger.warn("视图渲染耗时较长: {}ms - {}", duration, viewName);
} else if (logger.isDebugEnabled()) {
logger.debug("视图渲染耗时: {}ms - {}", duration, viewName);
}
}
}
}
安全考虑: Thymeleaf默认会对所有动态内容进行HTML转义,这有助于防止XSS攻击。但在某些情况下需要注意:
<!-- 安全:自动转义 -->
<p th:text="${userInput}"></p> <!-- 用户输入的HTML会被转义 -->
<!-- 危险:需要手动转义 -->
<div th:utext="${trustedHtml}"></div> <!-- 只有完全信任的内容才使用utext -->
<!-- 安全处理用户内容 -->
<div th:utext="${#strings.escapeXml(userContent)}"></div>
与前端框架集成: 在现代Web开发中,常常需要将Thymeleaf与Vue.js、React等前端框架结合使用:
<div id="app">
<!-- Vue.js使用Thymeleaf传递的初始数据 -->
<script th:inline="javascript">
/*<![CDATA[*/
window.APP_CONFIG = {
apiBaseUrl: /*[[@{/api}]]*/ '/api',
currentUser: /*[[${user}]]*/ null,
features: /*[[${features}]]*/ []
};
/*]]>*/
</script>
<!-- Thymeleaf渲染服务器端内容 -->
<div th:if="${user != null}">
<h1>欢迎,<span th:text="${user.name}">用户</span>!</h1>
<!-- Vue.js接管后续交互 -->
<div v-cloak>
<user-dashboard :user="userData"></user-dashboard>
</div>
</div>
</div>
<script th:src="@{/js/vue-app.js}"></script>
这种混合模式结合了服务器端渲染的SEO优势和客户端渲染的交互体验,在实际项目中非常实用。
通过以上这些实践,Thymeleaf不仅能满足基本的模板渲染需求,还能适应复杂的现代Web应用开发。关键是要根据项目实际情况,合理组织代码结构,平衡开发效率和运行性能。



被折叠的 条评论
为什么被折叠?



