Thymeleaf 是一个现代化的服务器端 Java 模板引擎,在 Spring Boot 项目中使用它可以方便地将 Java 代码和 HTML 页面进行整合,生成动态的 Web 页面。以下将详细介绍在 Spring Boot 中如何使用 Thymeleaf 模板引擎。
1. 添加依赖
如果你使用的是 Maven 项目,在 pom.xml
中添加 Thymeleaf 的依赖。在使用 Spring Initializr 创建项目时选择了 Thymeleaf 依赖,会自动添加以下内容;若未选择,可手动添加:
收起
xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 配置 Thymeleaf
Spring Boot 对 Thymeleaf 有默认的配置,一般情况下无需额外配置。默认配置如下:
- 模板文件位置:
src/main/resources/templates
- 模板文件后缀:
.html
- 缓存:开发环境建议关闭缓存,在
application.properties
或application.yml
中进行配置。
application.properties
配置示例
收起
properties
spring.thymeleaf.cache=false
application.yml
配置示例
收起
yaml
spring:thymeleaf:cache: false
3. 创建控制器
创建一个控制器类,用于处理 HTTP 请求,并将数据传递给 Thymeleaf 模板。以下是一个简单的示例:
收起
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;import java.util.ArrayList;
import java.util.List;@Controller
public class HelloController {@GetMapping("/hello")public String hello(Model model) {