要在Spring Boot中整合Thymeleaf模板引擎,請(qǐng)按照以下步驟操作:
在pom.xml
文件中添加Thymeleaf的依賴。將以下代碼添加到<dependencies>
標(biāo)簽內(nèi):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application.properties
或application.yml
文件中添加Thymeleaf的配置。以下是一些常用的配置選項(xiàng):
# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
或者使用YAML格式:
# application.yml
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
encoding: UTF-8
mode: HTML
在src/main/resources/templates
目錄下創(chuàng)建Thymeleaf模板文件。例如,創(chuàng)建一個(gè)名為index.html
的文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}">Title</title>
</head>
<body>
<h1 th:text="${message}">Hello, World!</h1>
</body>
</html>
創(chuàng)建一個(gè)Spring MVC控制器,用于處理請(qǐng)求并返回Thymeleaf模板。例如:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("title", "Thymeleaf Integration");
model.addAttribute("message", "Welcome to Thymeleaf integration with Spring Boot!");
return "index";
}
}
啟動(dòng)Spring Boot應(yīng)用程序,然后在瀏覽器中訪問(wèn)http://localhost:8080/
。你應(yīng)該能看到Thymeleaf模板引擎渲染的頁(yè)面。
這就是在Spring Boot中整合Thymeleaf模板引擎的方法?,F(xiàn)在你可以開(kāi)始使用Thymeleaf來(lái)構(gòu)建動(dòng)態(tài)HTML頁(yè)面了。