添加依赖:
在Spring Boot项目中,你需要确保已经包含了Thymeleaf的依赖。如果你使用的是Maven,可以在pom.xml
中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
对于Gradle项目,相应的依赖项为:
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
配置Thymeleaf:
Spring Boot默认提供了Thymeleaf的自动配置,通常情况下你无需额外配置即可工作。但如果你需要自定义配置,可以在application.properties
或application.yml
中进行设置。例如,指定模板文件的存放位置:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
这意味着Thymeleaf将在src/main/resources/templates/
目录下查找以.html
结尾的模板文件。
编写HTML模板:
在src/main/resources/templates/
目录下创建你的HTML文件。例如,创建一个index.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${pageTitle}">Default Title</title>
</head>
<body>
<h1 th:text="Hello, Thymeleaf!"></h1>
</body>
</html>
控制器处理: 在你的Spring控制器中,你可以返回一个视图名称,Thymeleaf会自动寻找对应的HTML模板并渲染数据。例如:
@Controller
public class HomeController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("pageTitle", "Thymeleaf Example");
return "index"; // 返回的字符串对应模板文件名(不包括后缀)
}
}
热加载:
如果你想在开发过程中实现HTML模板的热加载(即修改后自动重新加载),Spring Boot DevTools可以提供这个功能。只需在你的项目依赖中加入spring-boot-devtools
依赖:
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
Gradle:
developmentOnly 'org.springframework.boot:spring-boot-devtools'
DevTools默认开启自动重启特性,当你修改HTML、CSS、JavaScript或Java源码时,应用会自动重启,从而即时反映你的更改。
按照上述步骤,Thymeleaf会自动加载和解析你的HTML文件。