哦哇資訊網

SpringBoot與Thymeleaf模板入門整合篇

由 Java小老太 發表于 美食2022-12-14

1.1 認識 Thymeleaf

Thymeleaf 是一個流行的模板引擎,該模板引擎採用 Java 語言開發

模板引擎是一個技術名詞,是跨領域跨平臺的概念,在 Java 語言體系下有模板引擎,在 C#、PHP 語言體系下也有模板引擎,甚至在 JavaScript 中也會用到模板引擎技術,Java 生態下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(國產) 等。

Thymeleaf 對網路環境不存在嚴格的要求,既能用於 Web 環境下,也能用於非 Web 環境下。在非 Web 環境下,他能直接顯示模板上的靜態資料;在 Web 環境下,它能像 Jsp 一樣從後臺接收資料並替換掉模板上的靜態資料。它是基於 HTML 的,以 HTML 標籤為載體,Thymeleaf 要寄託在 HTML 標籤下實現。

SpringBoot 集成了 Thymeleaf 模板技術,並且 Spring Boot 官方也推薦使用 Thymeleaf 來替代 JSP 技術,Thymeleaf 是另外的一種模板技術,它本身並不屬於 Spring Boot,Spring Boot只是很好地整合這種模板技術,作為前端頁面的資料展示,在過去的 Java Web 開發中,我們往往會選擇使用 Jsp 去完成頁面的動態渲染,但是 jsp 需要翻譯編譯執行,效率低

Thymeleaf 的官方網站:www。thymeleaf。org

Thymeleaf 官方手冊:www。thymeleaf。org/doc/tutoria…

11。2 SpringBoot整合 Thymeleaf

11。2。1 新建一個springboot專案,專案名稱:037-springboot-thymeleaf-first

建立 Spring Boot 專案,新增 web 和 Thymeleaf 依賴\

按照這種方式建立後,pom。xml 檔案下會自動新增如下依賴

<!——SpringBoot 整合 Thymeleaf 的起步依賴——> org。springframework。boot spring-boot-starter-thymeleaf<!——SpringBoot 開發 web 專案的起步依賴——> org。springframework。boot spring-boot-starter-web複製程式碼

11。2。2 在Springboot的核心配置檔案application。properties中對Thymeleaf進行配置

#thymeleaf 頁面的快取開關,預設 true 開啟快取#建議在開發階段關閉 thymeleaf 頁面快取,目的實時看到頁面spring。thymeleaf。cache=false複製程式碼

其實什麼都不用配置就可以工作,因為基本 Thymeleaf 的配置都有預設值

#字首:#thymeleaf 模版字首,預設可以不寫spring。thymeleaf。prefix=classpath:/templates/#字尾:#thymeleaf 模版字尾,預設可以不寫spring。thymeleaf。suffix=。html複製程式碼

11。2。3 建立 ThymeleafControlle去對映到模板頁面(和 SpringMVC基本一致)

@Controllerpublic class ThymeleafController {@RequestMapping(value = “/thymeleaf/index”)public String index(Model model) { model。addAttribute(“data”,“SpringBoot 成功整合 Thymeleaf 模版!”); return “index”; }}複製程式碼

11。2。4 在src/main/resources 的templates 下新建一個 index。html頁面用於展示資料

HTML 頁面的元素中加入以下屬性:

<!DOCTYPE html> SpringBoot 整合 Thymeleaf <!——Thymeleaf 前端框架以 Html 為載體——>

複製程式碼

11。2。5 啟動程式,

SpringBoot與Thymeleaf模板入門整合篇

右鍵->檢視頁面原始碼

SpringBoot與Thymeleaf模板入門整合篇

注 意 : Springboot 用 使 用 thymeleaf 作 為 視 圖 展 示 , 約 定 將 模 板 文 件 放 置 在src/main/resource/templates 目錄下,靜態資源放置在 src/main/resource/static 目錄下

11。3 Thymeleaf 的表示式

11。3。6 新建一個springboot專案,專案名稱:038-springboot-thymeleaf-expression

1)建立SpringBoot的web專案並使用模版引擎

SpringBoot與Thymeleaf模板入門整合篇

SpringBoot與Thymeleaf模板入門整合篇

SpringBoot與Thymeleaf模板入門整合篇

SpringBoot與Thymeleaf模板入門整合篇

2)pom。xml中應該有如下兩個依賴

<!——SpringBoot 整合 Thymeleaf 模版引擎的起步依賴——> org。springframework。boot spring-boot-starter-thymeleaf<!——SpringBoot 的 web 專案起步依賴——> org。springframework。boot spring-boot-starter-web複製程式碼

3)在 application。properties中設定 thymeleaf 引數

#設定 thymeleaf 頁面快取失效spring。thymeleaf。cache=false#thymeleaf 模版字首,預設值,可選項spring。thymeleaf。prefix=classpath:/templates/#thymeleaf 模版字尾,預設值,可選項spring。thymeleaf。suffix=。html複製程式碼

4)建立實體 User 實體類

建立 User 實體類,為後續演示提供資料

@Datapublic class User { private Integer id; private String name; private String phone; private String address;}複製程式碼

5)建立 ThymeleafController 類

@Controllerpublic class ThymeleafController { @RequestMapping(value = “/thymeleaf/index”) public String index(Model model) { model。addAttribute(“data”,“SpringBoot 整合 Thymeleaf 模版!”); return “index”; }}複製程式碼

6)在src/main/resources/templates 在建立 html 頁面

<!DOCTYPE html> Thymeleaf‘Index 複製程式碼

7)測試

SpringBoot與Thymeleaf模板入門整合篇

11。3。7 標準變量表達式

注意:th:text=“” 是Thymeleaf 的一個屬性,用於文字的顯示

8)語法 。。。 9)說明 標準變量表達式用於訪問容器(tomcat)上下文環境中的變數,功能和EL中的{。。。}\ 9)說明\ 標準變量表達式用於訪問容器(tomcat)上下文環境中的變數,功能和 EL 中的 。。。 9)說明 標準變量表達式用於訪問容器(tomcat)上下文環境中的變數,功能和EL中的{} 相同。Thymeleaf 中的變量表達式使用 ${變數名} 的方式獲取 Controller 中 model 其中的資料

10)案例演示

建立一個方法,將使用者資訊存放到 model 中,thymeleaf 模版頁面獲取物件資訊

●在 ThymeleafController 中新增方法,向 model 放入 User 物件

@RequestMapping(value = “/thymeleaf/user”)public String user(Model model) { User user = new User(); user。setId(1); user。setName(“張三”); user。setPhone(“13700000000”); user。setAddress(“北京市亦莊經濟開發區”); model。addAttribute(“user”,user); return “user”;}複製程式碼

在 templates 目錄下建立 user。html 頁面獲取 User 物件資料

<!DOCTYPE html> 展示使用者物件資訊

展示 User 使用者資訊:

使用者編號:
使用者姓名:
使用者手機號:
使用者地址:
複製程式碼

瀏覽器訪問 http://localhost:8080/thymeleaf /user 測試

SpringBoot與Thymeleaf模板入門整合篇

### 11。3。8 選擇變量表達式 選擇變量表達式 (瞭解,不推薦使用)複製程式碼

11)語法:*{。。。}

12)說明

選擇變量表達式,也叫星號變量表達式,使用 th:object 屬性來繫結物件

選擇表示式首先使用 th:object 來繫結後臺傳來的 User 物件,然後使用 * 來代表這個物件,後面 {} 中的值是此物件中的屬性。

選擇變量表達式 *{。。。} 是另一種類似於標準變量表達式 ${。。。} 表示變數的方法

選擇變量表達式在執行時是在選擇的物件上求解,而${。。。}是在上下文的變數 Model 上求解,這種寫法比標準變量表達式繁瑣,只需要大家瞭解即可

13)案例演示

在 user。html 透過選擇變量表達式(星號表示式)獲取使用者資料

展示 User 使用者資訊(星號表示式,僅在 div 範圍內有效):

使用者編號:
使用者姓名:
使用者手機號:
使用者地址:
複製程式碼

- 瀏覽器訪問 http://localhost:8080/thymeleaf/ user 測試複製程式碼

SpringBoot與Thymeleaf模板入門整合篇

11。3。9 標準變量表達式和選擇變量表達式混合使用

標準變數和選擇變量表達式可以混合使用,也可以不混合使用,使用 th:object 進行物件的選擇,也可以直接使用 *{。。。} 獲取資料

在 user。html 模版中新增如下程式碼:

標準變量表達式和選擇變量表達式混用

=======標準變量表達式=======

使用者編號:
使用者姓名:
使用者手機號:
使用者地址:

=======選擇變量表達式=======

使用者編號:*{user。id} ==>
使用者姓名:*{user。name} ==>
使用者手機號:*{user。phone} ==>
使用者地址:*{user。address} ==>
複製程式碼

測試檢視結果

SpringBoot與Thymeleaf模板入門整合篇

11。3。10 URL 表示式

14)語法@{。。。}

15)說明

主要用於連結、地址的展示,可用於

這種方式比傳統方式的好處是,在 URL 表示式前加/,會自動加上上下文根,避免 404 找不到資源的情況。11。4。6 th:id\類似 html 標籤中的 id 屬性aaa11。4。7 th:name設定名稱\11。4。8 th:value類似 html 標籤中的 value 屬性,能對某元素的 value 屬性進行賦值\\11。4。9 th:attr該屬性也是用於給 HTML 中某元素的某屬性賦值,好處是可以給 html 中沒有定義的屬性動態的賦值。 複製程式碼

th:attr 屬性的使用

```

SpringBoot與Thymeleaf模板入門整合篇

11。4。10 th:text

用於文字的顯示,該屬性顯示的文字在標籤體中,如果是文字框,資料會在文字框外顯示,要想顯示在文字框內,使用 th:value;

11。4。11 th:object

用於資料物件繫結

通常用於選擇變量表達式(星號表示式)

11。4。12 th:onclick

th:onclick 的使用

<!——目前 thymeleaf 版本要求只能傳遞數字和布林值——>點選:顯示學生編號複製程式碼

11。4。13 th:style

設定樣式

點選:顯示學生編號複製程式碼

11。4。14 *th:each複製程式碼

這個屬性非常常用,比如從後臺傳來一個物件集合那麼就可以使用此屬性遍歷輸出,它與JSTL 中的類似,此屬性既可以迴圈遍歷集合,也可以迴圈遍歷陣列及 Map

28)遍歷List集合

A、在 ThymeleafController 中新增 eachList 方法,準備集合資料

@RequestMapping(“/each/list”)public String eachList(Model model){ List userList = new ArrayList(); for (int i = 0;i < 10;i++){ User user = new User(); user。setId(100 + i); user。setNick(“張” + i); user。setPhone(“1361234567” + i); user。setAddress(“北京市大興區” + i); userList。add(user); } model。addAttribute(“userList”,userList); return “each”;}複製程式碼

B、建立 eachList。html 對 List 集合進行遍歷

<!DOCTYPE html> 迴圈遍歷 List 集合

th:each 迴圈遍歷 List 集合

1。user:當前物件的變數名
2。userStat:當前物件的狀態變數名
3。${userList}:迴圈遍歷的集合
4。變數名自定義
複製程式碼

程式碼說明

th:each=“user, iterStat : userlist”中的{userlist}“ 中的 userlist”中的{userList} 是後臺傳過來的集合

◼ user

定義變數,去接收遍歷${userList}集合中的一個數據

◼ iterStat

${userList} 迴圈體的資訊

◼ 其中 user 及 iterStat 自己可以隨便取名

◼ interStat 是迴圈體的資訊,透過該變數可以獲取如下資訊

index: 當前迭代物件的 index (從 0 開始計算)

count: 當前迭代物件的個數(從 1 開始計算) 這兩個用的較多

size: 被迭代物件的大小

current: 當前迭代變數

even/odd: 布林值,當前迴圈是否是偶數/奇數(從 0 開始計算)

first: 布林值,當前迴圈是否是第一個

last: 布林值,當前迴圈是否是最後一個

注意:迴圈體資訊 interStat 也可以不定義,則預設採用迭代變數加上 Stat 字尾,即 userStat

C、瀏覽器 訪問測試

SpringBoot與Thymeleaf模板入門整合篇

29)遍歷Map集合

D、在 ThymeleafController 中新增 eachMap 方法

@RequestMapping(value = “/each/map”)public String eachMap(Model model) { Map userMaps = new HashMap(); for (int i = 0; i < 10; i++) { User user = new User(); user。setId(i); user。setName(“李四”+i); user。setPhone(“1390000000”+i); user。setAddress(“天津市”+i); userMaps。put(i,user); } model。addAttribute(“userMaps”,userMaps); return “eachMap”;}複製程式碼

E、新增 eachMap。html頁面對Map集合進行遍歷

<!DOCTYPE html> 迴圈遍歷 Map 集合

th:each 迴圈遍歷 Map 集合

複製程式碼

程式碼說明

th:each=“userMap,userMapStat:${userMaps}” ,用 userMap 變數接收每次遍歷的結果,封裝

為一個鍵值對,userMapStat 狀態

userMap。key:獲取當前鍵值對中的 key

userMap。value:獲取當前鍵值對中的 value

F、瀏覽器訪問測試

SpringBoot與Thymeleaf模板入門整合篇

30)遍歷Array陣列

G、在 ThymeleafController 中的 eachArray 方法中準備陣列資料

@RequestMapping(value = “/each/array”)public String eachArray(Model model) { User[] userArray = new User[10]; for (int i = 0; i < 10; i++) { User user = new User(); user。setId(i); user。setName(“趙六”+i); user。setPhone(“1380000000”+i); user。setAddress(“深圳市”+i); userArray[i] = user; } model。addAttribute(“userArray”,userArray); return “eachArray”;}複製程式碼

H、在 eachArray。html 頁面對陣列進行遍歷(和 List 一樣)

<!DOCTYPE html> 迴圈遍歷 Array 陣列

複製程式碼

I、瀏覽器訪問測試

SpringBoot與Thymeleaf模板入門整合篇

31)比較複雜的迴圈案例

求:List 裡面放 Map ,Map 裡面又放的是 List

SpringBoot與Thymeleaf模板入門整合篇

J、在 ThymeleafController 的 each 方法中構造資料

@RequestMapping(value = “/each/all”)public String eachAll(Model model) { //list -> Map -> List -> User List>> myList = new ArrayList>>(); for (int i = 0; i < 2; i++) { Map> myMap = new HashMap>(); for (int j = 0; j < 2; j++) { List myUserList = new ArrayList(); for (int k = 0; k < 3; k++) { User user = new User(); user。setId(k); user。setName(“張三”+k); user。setPhone(“1350000000”+k); user。setAddress(“廣州市”+i); myUserList。add(user); } myMap。put(j,myUserList); } myList。add(myMap); } model。addAttribute(“myList”,myList); return “eachAll”;}複製程式碼

K、在 eachAll。html 頁面對複雜集合關係進行遍歷

<!DOCTYPE html> 迴圈遍歷複雜集合

迴圈遍歷複雜集合:list -> Map -> List -> User

Map 集合的 key:
複製程式碼

L、瀏覽器訪問測試

迴圈遍歷複雜集合

localhost:8090/property/each/all

C味

SpringBoot與Thymeleaf模板入門整合篇

11。4。15 條件判斷 32)th:if 33)th:unless

@RequestMapping(value = “/condition”)public String condition(HttpServletRequest request,Model model) { User user1 = null; model。addAttribute(“user1”,user1); User user2 = new User(); user2。setId(1001); user2。setName(“小嶽嶽”); user2。setPhone(“13900000000”); user2。setAddress(“北京市”); model。addAttribute(“user2”,user2); model。addAttribute(“sex”,1); User user3 = new User(); user3。setId(1002); user3。setName(“孫悅”); user3。setPhone(“13200000000”); user3。setAddress(“北京市”); model。addAttribute(“user3”,user3); request。getSession()。setAttribute(“user3”,user3); return “condition”;}複製程式碼

condition。html 頁面

<!DOCTYPE html> 條件判斷

th:if 用法:如果滿足條件顯示,否則相反

男:
女:

th:unless 用法:與 th:if 用法相反,即對條件判斷條件取反

男:
女:

使用者未登入

使用者姓名:

從 session 中獲取值

複製程式碼

34)th:switch/th:case

switch,case 判斷語句

th:switch/th:case 用法

性別:男
性別:女
性別:保密
複製程式碼

一旦某個 case 判斷值為 true ,剩餘的 case 預設不執行 ,“ ”表示默的 認的 case ,前面的 case 都不匹配時候,執行預設的 case

*

35)瀏覽器訪問測試

SpringBoot與Thymeleaf模板入門整合篇

11。4。16 th:inline

th:inline 有三個取值型別 (text, javascript 和 none),值為 none 什麼都不做,沒有效果

內斂文字(th:inline=”text” )

內斂文字表示式不依賴於 html 標籤,直接使用 內斂表示式[[ 表示式]]即可獲取動態資料,但必須要求在父級標籤上加 th:inline = “text”屬性

A、在 ThymeleafController 類中新增方法

@RequestMapping(value = “/inline”)public String inlineText(Model model) { User user = new User(); user。setId(1003); user。setName(“傑克”); user。setPhone(“13899990000”); user。setAddress(“天津市”); model。addAttribute(“user”,user); return “inline ”;}複製程式碼

B、建立 inline。html

<!DOCTYPE html> 內斂文字

標準變量表達式(展示資料)

使用者編號:
使用者姓名:
使用者手機號:
使用者地址:

內斂文字 th:inline=“text”

使用者編號:
[[${user。id}]]

使用者姓名:[[${user。name}]]
使用者手機號:[[${user。phone}]]
使用者地址:[[${user。address}]]
複製程式碼

C、瀏覽器訪問測試

SpringBoot與Thymeleaf模板入門整合篇

注意:一般我們將 th:inline=“text” 放到 標籤中\

●內斂指令碼(th:inline=”javascript” )

th:inline=”javascript” 在 js 程式碼中獲取後臺的動態資料

D、在 inline。html 頁面上,新增如下程式碼

function showInlineJavaScript() { alert(“歡迎 ” + [[${user。name}]] + “ 到我院指導工作!聯絡方式: ” + [[${user。phone}]]); } 複製程式碼

E、瀏覽器訪問測試

SpringBoot與Thymeleaf模板入門整合篇

11。5 Thymeleaf字面量 字面量:對應資料型別的合法取值,可以在 html 頁面直接使用,不需要後臺傳遞

在 ThymeleafController 類中新增方法並準備資料

@RequestMapping(value = “/literal”)public String literal(Model model) { model。addAttribute(“success”,true); model。addAttribute(“flag”,false); User user = new User(); user。setId(1004); user。setName(“賈玲”); user。setPhone(“13777777777”); user。setAddress(“北京市”); model。addAttribute(“user”,user); return “literal”;}複製程式碼

建立 literal。html 頁面

<!DOCTYPE html> Thymeleaf 字面量複製程式碼

11。5。1 文字字面量\複製程式碼

用單引號’。。。‘包圍的字串為文字字面量

文字字面量:用單引號’。。。‘包圍的字串

檢視使用者:文字字面的路徑使用
複製程式碼

11。5。3 boolean字面量

boolean 字面量

執行成功
執行不成功
複製程式碼

11。5。4 null字面量

null 字面量

使用者不為空
使用者不為空(使用 th:unless 取反)
複製程式碼

11。6 Thymeleaf字串拼接

文字字面量使用“+”拼接字串

另一種更優雅的方式:使用“|要拼接的內容|”減少字串拼接的加號

複製程式碼

11。7 Thymeleaf 運算子

三元運算 :表示式?” 正確結果”:” 錯誤結果”

算術運算: :+ , - , * , / , %

關係比較: :> , < , >= , <= ( gt , lt , ge , le )

相等判斷: :== , != ( eq , ne )

@RequestMapping(value = “/operator”)public String operator(Model model) { model。addAttribute(“sex”,1); return “operator”;}複製程式碼

<!DOCTYPE html> 運算子

三元運算子



20*8=
20/8=
20+8=
20-8=
2”>5>2 是真的
5 gt 2 是真的
複製程式碼

運算子

C合

localhost:8090/property/operator

三元運算子

出郵

20*8-160

20/8-2。5

20+8-28

20-8-12

5-2是真的

5gt2是真的

SpringBoot與Thymeleaf模板入門整合篇

11。8 Thymaleaf表示式基本物件

模板引擎提供了一組內建的物件,這些內建的物件可以直接在模板中使用,這些物件由 #號開始引用,我們比較常用的內建物件

11。8。1 建立 SpringBoot專案並整合 thymeleaf 框架

SpringBoot與Thymeleaf模板入門整合篇

SpringBoot與Thymeleaf模板入門整合篇

SpringBoot與Thymeleaf模板入門整合篇

SpringBoot與Thymeleaf模板入門整合篇

11。8。2 #request

#request 相 當 於 httpServletRequest 對 象 , 這 是 3。x 版 本 , 若 是 2。x 版 本 使 用

#httpServletRequest,在頁面獲取應用的上下文根,一般在 js 中請求路徑中加上可以避免 404

<!DOCTYPE html> Thymeleaf 表示式基本物件 複製程式碼

11。8。3 #session

相當於 HttpSession 物件,這是 3。x 版本,若是 2。x 版本使用#httpSession

在後臺方法中向 session 中放資料

@Controllerpublic class UserController { @RequestMapping(value = “/index”) public String index(HttpServletRequest request,Model model,Integer id) { model。addAttribute(“username”,“lisi”); request。getSession()。setAttribute(“data”,“sessionData”); return “index”; }}複製程式碼

從頁面獲取資料

從SESSION中獲取值




複製程式碼

11。9 Thymeleaf表示式功能物件(瞭解)

模板引擎提供的一組功能性內建物件,可以在模板中直接使用這些物件提供的功能方法工作中常使用的資料型別,如集合,時間,數值,可以使用 Thymeleaf 的提供的功能性物件來處理它們;

內建功能物件前都需要加#號,內建物件一般都以 s 結尾

官方手冊:www。thymeleaf。org/doc/tutoria…

#dates: java。util。Date 物件的實用方法:

#calendars: 和 dates 類似, 但是 java。util。Calendar 物件;

#numbers: 格式化數字物件的實用方法;

#strings: 字串物件的實用方法: contains, startsWith, prepending/appending 等;

#objects: 對 objects 操作的實用方法;

#bools: 對布林值求值的實用方法;

#arrays: 陣列的實用方法;

#lists: list 的實用方法,比如

#sets: set 的實用方法;

#maps: map 的實用方法;

#aggregates: 對陣列或集合建立聚合的實用方法;

@Controllerpublic class UserController { @RequestMapping(value = “/function”) public String function(Model model) { model。addAttribute(“time”,new Date()); model。addAttribute(“data”,“SpringBootHelloWorld”); return “function”; }}複製程式碼

<!DOCTYPE html> Title

TAG: userthModel11程式碼