1. 安裝和配置Spring Boot
首先,我們需要安裝并配置Spring Boot框架。您可以通過訪問Spring官方網(wǎng)站(https://spring.io)來獲取最新的Spring Boot版本。安裝完成后,您可以按照Spring Boot的官方文檔進(jìn)行配置,以便開始使用。
2. 添加Thymeleaf依賴
接下來,我們需要在我們的Spring Boot項目中添加Thymeleaf的依賴。在項目的pom.xml文件中,添加以下依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>3. 創(chuàng)建Thymeleaf模板
在我們的Spring Boot項目中,我們需要創(chuàng)建Thymeleaf模板,用于渲染動態(tài)內(nèi)容。首先,我們可以在src/main/resources/templates目錄下創(chuàng)建一個HTML文件,命名為index.html。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot集成Thymeleaf實例</title>
</head>
<body>
<h3>歡迎使用Spring Boot集成Thymeleaf</h3>
<p th:text="'當(dāng)前時間:' + ${currentDate}" />
<ul>
<li th:each="item : ${items}" th:text="${item}" />
</ul>
</body>
</html>4. 創(chuàng)建控制器
接下來,我們需要創(chuàng)建一個控制器類來處理對Web頁面的請求,并將數(shù)據(jù)傳遞給Thymeleaf模板進(jìn)行渲染。在我們的Spring Boot項目中,創(chuàng)建一個名為HomeController的Java類,并添加以下代碼:
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("currentDate", new Date());
model.addAttribute("items", Arrays.asList("Item 1", "Item 2", "Item 3"));
return "index";
}
}5. 運行應(yīng)用程序
現(xiàn)在,我們可以運行我們的Spring Boot應(yīng)用程序,并通過訪問http://localhost:8080來查看Thymeleaf模板渲染的動態(tài)Web頁面。
6. 添加靜態(tài)資源
有時候我們需要在Web頁面中使用一些靜態(tài)資源,比如CSS文件、JavaScript文件或圖像。為了添加靜態(tài)資源,我們可以在src/main/resources/static目錄下創(chuàng)建一個文件夾,并將相應(yīng)的資源文件放置在該文件夾中。
7. 總結(jié)
通過本文,我們了解了如何使用Spring Boot集成Thymeleaf來創(chuàng)建動態(tài)Web頁面。我們學(xué)習(xí)了安裝和配置Spring Boot框架的步驟,添加Thymeleaf的依賴,創(chuàng)建Thymeleaf模板以及創(chuàng)建控制器類來處理請求和傳遞數(shù)據(jù)。最后,我們還學(xué)習(xí)了如何添加靜態(tài)資源到我們的應(yīng)用程序中。希望這篇文章能夠幫助您在開發(fā)Web應(yīng)用程序時更好地使用Spring Boot與Thymeleaf。