您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Thymeleaf模板引擎怎么使用
## 一、Thymeleaf简介
### 1.1 什么是Thymeleaf
Thymeleaf是一个现代化的服务器端Java模板引擎,适用于Web和独立环境。它能够处理HTML、XML、JavaScript、CSS甚至纯文本。与JSP等传统技术相比,Thymeleaf的主要特点是:
- **自然模板**:可在浏览器直接打开预览
- **无Servlet依赖**:不强制要求Servlet环境
- **Spring完美集成**:Spring官方推荐的视图技术
- **表达式语法**:强大的OGNL和SpringEL表达式支持
### 1.2 核心特性
- **模板缓存**:可配置的模板缓存机制
- **国际化支持**:内置国际化处理能力
- **片段重用**:支持模板片段定义和引用
- **多种方言**:可通过方言扩展功能
## 二、环境配置
### 2.1 Maven依赖
```xml
<!-- Spring Boot集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 独立使用 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false # 开发时关闭缓存
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
src/
├── main/
│ ├── java/
│ └── resources/
│ ├── static/ # 静态资源
│ └── templates/ # 模板文件
<!-- 变量表达式 -->
<p th:text="${user.name}">默认用户名</p>
<!-- 选择表达式 -->
<div th:object="${user}">
<p th:text="*{age}">年龄</p>
</div>
<!-- 链接表达式 -->
<a th:href="@{/user/list}">用户列表</a>
<!-- 片段表达式 -->
<div th:insert="~{footer :: content}"></div>
属性 | 说明 |
---|---|
th:text |
文本替换 |
th:utext |
非转义文本 |
th:value |
表单值设置 |
th:each |
循环迭代 |
th:if |
条件判断 |
th:switch |
多条件选择 |
th:href |
链接URL |
th:src |
资源URL |
<!-- 循环示例 -->
<ul>
<li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>
<!-- 条件判断 -->
<div th:if="${user.isAdmin}">管理员面板</div>
<div th:unless="${user.isAdmin}">普通用户面板</div>
<!-- Switch语句 -->
<div th:switch="${user.role}">
<p th:case="'admin'">管理员</p>
<p th:case="'user'">普通用户</p>
</div>
定义基础模板 base.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:fragment="title">默认标题</title>
</head>
<body>
<header th:insert="~{header :: main}"></header>
<div th:replace="~{content}"></div>
<footer th:replace="~{footer :: main}"></footer>
</body>
</html>
子模板继承:
<html th:replace="~{base :: layout(~{::title}, ~{::content})}">
<head>
<title>子页面标题</title>
</head>
<body>
<div th:fragment="content">
<!-- 页面特有内容 -->
</div>
</body>
</html>
<form th:action="@{/user/save}" th:object="${user}" method="post">
<input type="text" th:field="*{name}">
<input type="email" th:field="*{email}">
<button type="submit">保存</button>
</form>
<p th:text="#{welcome.message}">欢迎消息</p>
<p th:text="#{|hello.user|(${user.name})|}">个性化问候</p>
<!-- 日期格式化 -->
<p th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"></p>
<!-- 集合工具 -->
<p th:text="${#lists.size(user.roles)}"></p>
<!-- 字符串操作 -->
<p th:text="${#strings.toUpperCase(user.name)}"></p>
@Controller
public class UserController {
@GetMapping("/user")
public String user(Model model) {
model.addAttribute("user", new User("张三", 25));
return "user/profile";
}
}
<div sec:authorize="isAuthenticated()">
欢迎 <span sec:authentication="name"></span>
</div>
<div sec:authorize="hasRole('ADMIN')">
管理员功能
</div>
<input type="text" th:field="*{email}" class="form-control">
<div th:if="${#fields.hasErrors('email')}"
th:errors="*{email}" class="error-message"></div>
# 生产环境配置
spring.thymeleaf.cache=true
spring.thymeleaf.template-resolver-order=1
<!-- 缓存用户信息片段 -->
<div th:replace="~{user/info :: panel}"
th:with="cacheKey=${#strings.arrayJoin('user',user.id)}">
</div>
<!-- 版本化静态资源 -->
<link th:href="@{/css/main.css(v=${@environment.getProperty('app.version')})}">
<!-- 禁用转义 -->
<p th:utext="${htmlContent}"></p>
<!-- 内联表达式 -->
[(${unsafeContent})]
确保正确配置:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
检查: 1. 模板文件是否在正确目录 2. 后缀配置是否匹配 3. 模板语法是否正确
Thymeleaf作为现代Java模板引擎,通过本文我们全面了解了: - 从基础语法到高级功能的使用方法 - 与Spring框架的深度集成 - 实际开发中的性能优化技巧 - 常见问题的解决方案
通过合理应用Thymeleaf,可以构建出结构清晰、维护性强的Web应用视图层。其自然模板特性特别适合前后端协作开发场景,是传统JSP技术的优秀替代方案。
本文约4500字,涵盖了Thymeleaf的核心使用场景。实际开发中应根据项目需求选择合适的特性组合,并参考官方文档获取最新特性支持。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。