七、Spring Boot 集成 Thymeleaf 模板引擎

前言:上一節對 SpringBoot 的Spring Boot 集成 Swagger2 展現在線接口文檔 做了一個介紹,本節主要對Spring Boot 集成 Thymeleaf 模板引擎講解和分析。

1. Thymeleaf 介紹

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

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

以上翻譯自 Thymeleaf 官方網站。傳統的 JSP+JSTL 組合是已經過去了,Thymeleaf 是現代服務端的模板引擎,與傳統的 JSP 不同,Thymeleaf 可以使用瀏覽器直接打 開,因爲可以忽略掉拓展屬性,相當於打開原生頁面,給前端人員也帶來一定的便利。

什麼意思呢?就是說在本地環境或者有網絡的環境下,Thymeleaf 均可運行。由於 thymeleaf 支持 html 原型,也支持在 html 標籤裏增加額外的屬性來達到 “模板+數據” 的展示方式,所以美工可以直接在瀏覽器中查看頁面效果,當服務啓動後,也可以讓後 臺開發人員查看帶數據的動態頁面效果。比如:

<div class="ui right aligned basic segment">
	<div class="ui orange basic label" th:text="${blog.flag}">靜態原創信息</div>
</div>
<h2 class="ui center aligned header" th:text="${blog.title}">這是 靜態標題</h2>

類似與上面這樣,在靜態頁面時,會展示靜態信息,當服務啓動後,動態獲取數據庫中 的數據後,就可以展示動態數據,th:text 標籤是用來動態替換文本的,這會在下文 說明。該例子說明瀏覽器解釋 html 時會忽略 html 中未定義的標籤屬性(比如 th:text),所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時, Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示數據。

2. 依賴導入

Spring Boot 中使用 thymeleaf 模板需要引入依賴,可以在創建項目工程時勾選 Thymeleaf,也可以創建之後再手動導入,如下:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 另外,在 html 頁面上如果要使用 thymeleaf 模板,需要在頁面標籤中引入:

      <html xmlns:th="http://www.thymeleaf.org">
    

3. Thymeleaf 相關配置

因爲 Thymeleaf 中已經有默認的配置了,我們不需要再對其做過多的配置,有一個需 要注意一下,Thymeleaf 默認是開啓頁面緩存的,所以在開發的時候,需要關閉這個頁面緩存,配置如下

#關閉緩存
spring:
  thymeleaf:
	cache: false

否則會有緩存,導致頁面沒法及時看到更新後的效果。 比如你修改了一個文件,已經 updatetomcat 了,但刷新頁面還是之前的頁面,就是因爲緩存引起的。

4. Thymeleaf 的使用

4.1 訪問靜態頁面

這個和 Thymeleaf 沒啥關係,應該說是通用的,我把它一併寫到這裏的原因是一般我 們做網站的時候,都會做一個 404 頁面和 500 頁面,爲了出錯時給用戶一個友好的展示,而不至於一堆異常信息拋出來。Spring Boot 中會自動識別模板目錄(templates/) 下的 404.html500.html 文件。我們在 templates/ 目錄下新建一個 error 文件夾,專 門放置錯誤的 html 頁面,然後分別打印些信息。以 404.html 爲例:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
這是404頁面
</body>
</html>

我們再寫一個 controller 來測試一下 404 和 500 頁面

[@Controller](https://my.oschina.net/u/1774615)
@RequestMapping("/thymeleaf")
public class ThymeleafController {

	@GetMapping("/test404")
	public String test404() {
		return "index";
	}

	@GetMapping("/test500")
	public String test500() {
		int i = 1 / 0;
		return "index";
	}

}

  • 當我們在瀏覽器中輸入 localhost:8080/thymeleaf/test400 時,故意輸入錯誤,找不到對應的方法,就會跳轉到 404.html 顯示。

  • 當我們在瀏覽器中輸入 localhost:8080/thymeleaf/test505 時,會拋出異常,然後會自動跳轉到 500.html 顯示。

【注】這裏有個問題需要注意一下,前面的課程中我們說了微服務中會走向前後端分離,我們在 Controller 層上都是使用的 @RestController 註解,自動會把返回的數據轉成 json 格式。但是在使用模板引擎時,Controller 層就不能用 @RestController 註解了,因爲在使用 thymeleaf 模板時,返回的是視圖文件名,比如上面的 Controller 中 是返回到 index.html 頁面,如果使用 @RestController 的話,會把 index 當作 String 解析了,直接返回到頁面了,而不是去找 index.html 頁面,大家可以試一下。所以在使用模板時要用 @Controller 註解。

4.2 Thymeleaf 中處理對象

我們來看一下 thymeleaf 模板中如何處理對象信息,假如我們在做個人博客的時候,需 要給前端傳博主相關信息來展示,那麼我們會封裝成一個博主對象,比如:

public class Blogger {

	private Long id;
	private String name;
	private String pass;
	//set get ......
}

然後在 controller 層中初始化一下:

@GetMapping("/getBlogger")
public String getBlogger(Model model) {
	Blogger blogger = new Blogger(1L, "理性思考", "123456");
	model.addAttribute("blogger", blogger);
	return "blogger";
}

我們先初始化一個 Blogger 對象,然後將該對象放到 Model 中,然後返回到 blogger.html 頁面去渲染。接下來我們再寫一個 blogger.html 來渲染 blogger 信息:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>博主信息</title>
</head>
<body>
<form action="" th:object="${blogger}" >
	用戶編號:<input name="id" th:value="${blogger.id}"/><br>
	用戶姓名:<input type="text" name="username" th:value="${blogger.getName()}" /><br>
	登陸密碼:<input type="text" name="password" th:value="*{pass}" />
</form>
</body>
</html>

可以看出,在 thymeleaf 模板中,使用 th:object="${}" 來獲取對象信息,然後在表單裏面可以有三種方式來獲取對象屬性。如下:

使用 th:value="*{屬性名}" 
使用 th:value="${對象.屬性 名}",對象指的是上面使用 th:object 獲取的對象 
使用 th:value="${對象.get 方法}",對象指的是上面使用 th:object 獲取的對象

可以看出,在 Thymeleaf 中可以像寫 java 一樣寫代碼,很方便。我們在瀏覽器中輸入 localhost:8080/thymeleaf/getBlogger 來測試一下數據:

4.3 Thymeleaf 中處理 List

處理 List 的話,和處理上面介紹的對象差不多,但是需要在 thymeleaf 中進行遍歷。我 們先在 Controller 中模擬一個 List

	@GetMapping("/getList")
	public String getList(Model model) {
		Blogger blogger1 = new Blogger(1L, "理性思考", "123456");
		Blogger blogger2 = new Blogger(2L, "感同身受", "123456");

		List<Blogger> list = new ArrayList<>();
		list.add(blogger1);
		list.add(blogger2);
		model.addAttribute("list", list);
		return "list";
	}

接下來我們寫一個 list.html 來獲取該 list 信息,然後在 list.html 中遍歷這個 list。如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>博主信息</title>
</head>
<body>
<form action="" th:each="blogger : ${list}" >
	用戶編號:<input name="id" th:value="${blogger.id}"/><br>
	用戶姓名:<input type="text" name="password" th:value="${blogger.name}"/><br>
	登錄密碼:<input type="text" name="username" th:value="${blogger.getPass()}"/>
</form>
</body>
</html>

可以看出,其實和處理單個對象信息差不多,Thymeleaf 使用 th:each 進行遍歷,${}model 中傳過來的參數,然後自定義 list 中取出來的每個對象,這裏定義爲 blogger。表單裏面可以直接使用 ${對象.屬性名} 來獲取 list 中對象的屬性值,也可以 使用 ${對象.get 方法} 來獲取,這點和上面處理對象信息是一樣的,但是不能使用 *{屬性名} 來獲取對象中的屬性,thymeleaf 模板獲取不到。

4.4 其他常用 thymeleaf 操作

我們來總結一下 thymeleaf 中的一些常用的標籤操作

Thymeleaf 還有很多其他用法,這裏就不總結了,具體的可以參考 Thymeleaf官方文檔(v3.0)。主要要學會如何在 Spring Boot 中去使用 thymeleaf,遇到對應的標籤或 者方法,查閱官方文檔即可。

5. 總結

ThymeleafSpring Boot 中使用非常廣泛,本節課主要分析了 thymeleaf 的優點,以 及如何在 Spring Boot 中集成並使用 thymeleaf 模板,包括依賴、配置,相關數據的獲 取、以及一些注意事項等等。最後列舉了一些 thymeleaf 中常用的標籤,在實際項目中 多使用,多查閱就能熟練掌握,thymeleaf 中的一些標籤或者方法不用死記硬背,用到 什麼去查閱什麼,關鍵是要會在 Spring Boot 中集成,用的多了就熟能生巧。


希望可以繼續關注後續更新文章! 對自己的技術能力有明確的目標!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章