1. 程式人生 > >玩轉 SpringBoot 2 快速整合 | Thymeleaf 篇

玩轉 SpringBoot 2 快速整合 | Thymeleaf 篇

前言

Thymeleaf是一個適用於Web和獨立環境的現代伺服器端Java模板引擎。

Thymeleaf的主要目標是為您的開發工作流程帶來優雅的自然模板 - 可以在瀏覽器中正確顯示的HTML,也可以用作靜態原型,從而在開發團隊中實現更強大的協作。

通過Spring Framework模組,與您喜歡的工具的大量整合,以及插入您自己的功能的能力,Thymeleaf是現代HTML5 JVM Web開發的理想選擇 - 儘管它可以做得更多。 ——摘抄自Thymeleaf官網介紹 連結:https://www.thymeleaf.org/index.html

Thymeleaf與Velocity或FreeMarker等其他模板引擎相比如何?

Velocity 和 FreeMarker 都是非常棒的軟體,但是它們處理模板問題的原理與Thymeleaf 完全不同。

Thymeleaf 非常強調自然模板化——允許模板成為工作原型,而其他兩個模板不允許這樣做——它的語法試圖(可以說)更乾淨,更符合當前 web開發的趨勢。另外,從架構的角度來看,Velocity 和 FreeMarker 都是順序文字處理器,而 Thymeleaf 是基於標記解析技術的。這允許 Thymeleaf 利用特定於基於標記的環境的有趣特性,特別是web。

無論如何,比較這些技術的最好方法是自己使用它們,並感覺哪個最適合你。

以上內容來自Thymeleaf官網 連結:

https://www.thymeleaf.org/faq.html#compare-other-engines

SpringBoot使用Thymeleaf 操作步驟

第一步是引入Thymeleaf starter依賴,具體程式碼如下:

		<!-- thymeleaf 相關依賴 -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

第二步是在 application.properties 新增 Thymeleaf 相關配置,具體配置如下:

server.port=8090
server.servlet.context-path=/sbe

#關閉 Thymeleaf 的快取開發過程中無需重啟
spring.thymeleaf.cache = false
#設定thymeleaf頁面的編碼
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#設定thymeleaf頁面的字尾
spring.thymeleaf.suffix=.html
#設定thymeleaf頁面的儲存路徑
spring.thymeleaf.prefix=classpath:/templates/

第三步是編寫訪問 Thymeleaf 頁面 Controller。

@Controller
@RequestMapping("/hello")
public class ThymeleafHelloWrodController {
	
	@RequestMapping("/thymeleaf")
	public String helloThymeleaf(Model model){
		model.addAttribute("hello","hello Thymeleaf!");
		return "hello/index";
	}
}

Thymeleaf 頁面程式碼如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p th:text="${hello}">hello</p>
</body>
</html>

測試

在遊覽器輸入訪問 Thymeleaf 頁面的 Controller 的 URL:http://localhost:8090/sbe/hello/thymeleaf 進行測試,測試結果如下: 在這裡插入圖片描述

小結

SpringBoot 使用 Thymeleaf 步驟如下:

  1. 引入Thymeleaf starter依賴
  2. 新增 Thymeleaf 相關配置
  3. 編寫訪問 Thymeleaf 頁面和 Controller

程式碼示例

具體程式碼示例請檢視我的GitHub 倉庫 springbootexamples 中的 spring-boot-2.x-thymeleaf 下的 helloword 包下檢視。

GitHub:https://github.com/zhuoqianmingyue/springbootexamples

如果您對這些感興趣,歡迎 star、或點贊給予支援!轉