Thymeleaf是一种用于Web和独立环境的现代化服务器端Java模板引擎。它被广泛用于Spring Boot项目中,用于在前端页面上渲染动态内容。
要在Spring Boot项目中整合和使用Thymeleaf
,可以按照以下步骤进行操作:
1:添加Thymeleaf依赖 在项目的构建文件(如pom.xml)中添加Thymeleaf的依赖项。例如,在Maven项目中,可以在<dependencies>标签下添加以下内容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2:配置Thymeleaf 在Spring Boot的配置文件(如application.properties或application.yml)中,可以配置Thymeleaf的相关属性。以下是一些常用的配置项:
# 设置模板页面的存放路径,默认为classpath:/templates/
spring.thymeleaf.prefix=classpath:/templates/
# 设置模板页面的后缀,默认为.html
spring.thymeleaf.suffix=.html
# 开启缓存,默认为true,建议在开发阶段设置为false
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false # 开发阶段建议禁用缓存
3:创建模板文件 在src/main/resources/templates目录下创建Thymeleaf模板文件,可以使用HTML语法编写,并在其中嵌入Thymeleaf的表达式。例如,可以创建一个名为"index.html"的模板文件
4:在Controller中使用Thymeleaf 在Spring Boot的Controller类中,可以通过使用@Controller注解和@RequestMapping注解来处理请求,并通过使用Model对象将数据传递给模板。例如:
@Controller
public class HomeController {
@RequestMapping("/home")
public String home(Model model) {
model.addAttribute("message", "Hello Thymeleaf!");
return "home";// 对应的模板文件为home.html
}
}
@Controller
public class HomeController {
@GetMapping("/home")
public String home(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "home"; // 对应的模板文件为home.html
}
}
5:模板渲染和展示数据 在模板文件中,可以使用Thymeleaf的表达式和语法来渲染动态内容。例如,在"index.html"模板中可以使用以下代码展示数据:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
Thymeleaf 模板引擎具有以下特点:
动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。
开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。
与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。
使用 Thymeleaf 来构建动态的前端页面
1.输出变量
<p>欢迎, <span th:text="${user.name}">User</span>!</p>
2.条件判断
<div th:if="${user.isAdmin()}">
<p>你是管理员。</p>
</div>
<div th:unless="${user.isAdmin()}">
<p>你不是管理员。</p>
</div>
3. 迭代列表
<ul>
<li th:each="item : ${items}">
<span th:text="${item}">Item</span>
</li>
</ul>
以上是整合和使用Thymeleaf的基本步骤。通过配置Thymeleaf、创建模板文件和在Controller中使用Thymeleaf,可以实现在Spring Boot项目中使用Thymeleaf来渲染动态内容。
本文章属于个人观点,做的不是很好,感谢大家的观看。