我們使用Spring Boot的時候我們都是通過@RestController來處理請求,是以傳回的内容為json對象。那麼如果需要渲染html頁面的時候,我們可能會需要一些模闆引擎,Thymeleaf是一個不錯的選擇。
Thymeleaf是一個XML/XHTML/HTML5模闆引擎,可用于Web與非Web環境中的應用開發。它是一個開源的Java庫,基于Apache License 2.0許可,由Daniel Fernández建立,該作者還是Java加密庫Jasypt的作者。
Thymeleaf提供了一個用于整合Spring MVC的可選子產品,在應用開發中,你可以使用Thymeleaf來完全代替JSP或其他模闆引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一種可被浏覽器正确顯示的、格式良好的模闆建立方式,是以也可以用作靜态模組化。你可以使用它建立經過驗證的XML與HTML模闆。相對于編寫邏輯或代碼,開發者隻需将标簽屬性添加到模闆中即可。接下來,這些标簽屬性就會在DOM(文檔對象模型)上執行預先制定好的邏輯。
Spring Boot 整合 Thymeleaf的步驟:
-
靜态資源通路
在我們開發Web應用的時候,需要引用大量的js、css、圖檔等靜态資源。
預設配置
Spring Boot預設提供靜态資源目錄位置需置于classpath下,目錄名需符合如下規則:
/static
/public
/resources
/META-INF/resources
舉例:我們可以在src/main/resources/目錄下建立static,在該位置放置一個圖檔檔案。啟動程式後,嘗試通路http://localhost:8080/D.jpg。如能顯示圖檔,配置成功。
2. 渲染web頁面
在動态HTML實作上Spring Boot依然可以完美勝任,并且提供了多種模闆引擎的預設配置支援,是以在推薦的模闆引擎下,我們可以很快的上手開發動态網站。
Spring Boot提供了預設配置的模闆引擎主要有以下幾種:
Thymeleaf
FreeMarker
Velocity
Groovy
Mustache
Spring Boot建議使用這些模闆引擎,避免使用JSP,若一定要使用JSP将無法實作Spring Boot的多種特性,
當你使用上述模闆引擎中的任何一個,它們預設的模闆配置路徑為:src/main/resources/templates。當然也可以修改這個路徑,具體如何修改,可在後續各模闆引擎的配置屬性中查詢并修改。
在此我使用Thymeleaf
3. 引入添加thymeleaf依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 配置application.properties
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-
#開發時關閉緩存,不然沒法看到實時頁面
spring.thymeleaf.cache=false
#thymeleaf end
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties這個類裡面有預設的配置。
spring-boot很多配置都有預設配置:
比如預設頁面映射路徑為classpath:/templates/*.html
同樣靜态檔案路徑為classpath:/static/
- 接下來我們就可以進行測試了,寫一個Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ThymeleafController {
@RequestMapping("/thymeleaf")
public String index(ModelMap map) {
// 加入一個屬性,用來在模闆中讀取
map.addAttribute("baidu", "http://www.baidu.com");
// return模闆檔案的名稱,對應src/main/resources/templates/index.html
System.out.println("hello world");
return "index";
}
}
- 編寫 index.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello World</h1>
<h1 th:text="${baidu}" >Hello World</h1>
<a th:href="${baidu}">百度一下 你就知道</a>
</body>
</html>
- 通路,結果,點選連結能打開百度首頁
Spring Boot 整合Thymeleaf