您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot如何使用Thymeleaf为模板
## 一、Thymeleaf简介
Thymeleaf是一款现代化的服务器端Java模板引擎,主要面向Web和独立环境开发。与JSP等传统模板引擎相比,Thymeleaf具有以下优势:
1. **自然模板**:支持HTML原型直接在浏览器中打开
2. **与Spring完美集成**:Spring官方推荐的模板引擎
3. **丰富的表达式语法**:支持OGNL、SpringEL等表达式
4. **模块化设计**:可扩展的模板解析器
## 二、SpringBoot集成Thymeleaf
### 1. 添加依赖
在`pom.xml`中添加starter依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
SpringBoot为Thymeleaf提供了自动配置类ThymeleafAutoConfiguration
,默认配置包括:
classpath:/templates/
.html
spring.thymeleaf.cache=false
)@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello Thymeleaf!");
return "hello"; // 对应templates/hello.html
}
}
src/main/resources/templates/hello.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<h1 th:text="${message}">默认文本</h1>
</body>
</html>
<p th:text="${user.name}">用户名</p>
<div th:object="${user}">
<p th:text="*{age}">年龄</p>
</div>
<a th:href="@{/user/{id}(id=${user.id})}">查看详情</a>
使用th:fragment
定义可重用片段:
layouts/base.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:fragment="title">默认标题</title>
</head>
<body>
<div th:fragment="header">公共头部</div>
<div th:fragment="content">
默认内容
</div>
<div th:fragment="footer">公共底部</div>
</body>
</html>
子模板引用:
<html th:replace="~{layouts/base :: layout(~{::title}, ~{::content})}">
<head>
<title>子页面标题</title>
</head>
<body>
<div th:replace="layouts/base :: header"></div>
<div th:replace="layouts/base :: content">
自定义内容
</div>
</body>
</html>
<form th:action="@{/user}" th:object="${user}" method="post">
<input type="text" th:field="*{name}">
<input type="text" th:field="*{email}">
<button type="submit">提交</button>
</form>
<div th:if="${user.vip}">
VIP用户专属内容
</div>
<div th:unless="${user.vip}">
普通用户内容
</div>
<div th:switch="${user.role}">
<p th:case="'admin'">管理员</p>
<p th:case="'user'">普通用户</p>
</div>
配置静态资源位置:
spring.mvc.static-path-pattern=/static/**
spring.web.resources.static-locations=classpath:/static/
模板中引用:
<link th:href="@{/static/css/style.css}" rel="stylesheet">
<script th:src="@{/static/js/app.js}"></script>
<p th:text="${#dates.format(user.createTime, 'yyyy-MM-dd')}"></p>
配置messages文件:
# messages.properties
welcome.message=Welcome!
模板中使用:
<p th:text="#{welcome.message}"></p>
模板不生效:
templates
目录xmlns:th
命名空间声明静态资源404:
static-path-pattern
配置缓存问题:
spring.thymeleaf.cache=false # 开发环境建议关闭
th:if
和th:unless
减少DOM渲染th:fragment
复用Thymeleaf作为SpringBoot的官方推荐模板引擎,提供了强大的功能和优雅的语法。通过本文的介绍,您应该已经掌握了: - 基本集成方法 - 常用模板语法 - 高级布局技巧 - 实际开发中的最佳实践
建议结合SpringBoot官方文档和Thymeleaf官方手册进一步深入学习,构建更加强大的Web应用。 “`
(全文约1700字)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。