1. 添加依赖
在项目的pom.xml文件中添加Spring Boot和Thymeleaf的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2. 配置Thymeleaf
在项目的application.properties或application.yml文件中配置Thymeleaf模板引擎的相关属性:
# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html;charset=UTF-8
spring.thymeleaf.cache=false
或者
# application.yml
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
servlet:
content-type: text/html;charset=UTF-8
cache: false
3. 创建Thymeleaf模板文件
在项目的src/main/resources/templates目录下创建一个HTML文件,例如index.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${message}">Hello, World!</h1>
</body>
</html>
4. 编写控制器类
创建一个控制器类,用于处理HTTP请求并返回视图名称:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Welcome to Spring Boot Thymeleaf Example!");
return "index";
}
}
5. 运行项目
启动Spring Boot应用,访问http://localhost:8080,可以看到渲染后的页面。