從零開始的Spring Boot(5、Spring Boot整合Thymeleaf)
- 2020 年 6 月 16 日
- 筆記
Spring Boot整合Thymeleaf
寫在前面
從零開始的Spring Boot(4、Spring Boot整合JSP和Freemarker)
//www.cnblogs.com/gaolight/p/13132021.html
從零開始的Spring Boot(6、Thymeleaf內置對象及表達式大全)
//www.cnblogs.com/gaolight/p/13138087.html
Thymeleaf中文文檔
//fanlychie.github.io/post/thymeleaf.html#2-1-1-…
一、Thymeleaf介紹
Thymeleaf的主要目標是將優雅的自然模板帶到開發工作流程中,並將HTML在瀏覽器
中正確顯示,並且可以作為靜態原型,讓開發團隊能更容易地協作。Thymeleaf 能夠處理
HTML,XML, JavaScript, CSs甚至純文本。
長期以來.jsp在視圖領域有非常重要的地位,隨著時間的變遷,出現了一位新的挑戰
者:Thymeleaf,Thymeleaf是原生的,不依賴於標籤庫.它能夠在接受原始HTML的地方進行編
輯和渲染因為它沒有與Servelet規範耦合,因此Thymeleaf模板能進入jsp所無法涉足的領域。
二、Thymeleaf的基本使用
- 創建項目;
創建項目springbootthymeleaf;
2.修改POM文件,添加Thynaleaf依賴;
<!–添加Thymeleaf啟動器依賴–>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.創建Controller;
package com.demo.springbootthymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class PageController {
@GetMapping(“/show”)
public String showPage(Model model){
model.addAttribute(“msg”,”Hello Thymeleaf”);
return “index”;
}
}
4.創建視圖;(html使用html4)
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“//www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title>標題</title>
</head>
<body>
<span th:text=”標題“></span>
<hr/>
<span th:text=”${msg}”></span>
</body>
</html>
5.運行啟動類,瀏覽器輸入//localhost:8080/show
三、Thymeleaf的變數輸出操作
命名空間: xmlns:th=”//www.thymeleaf.org」
字元串與變數輸出操作
th:text在頁面中輸出值
th:value可以將一個值放入到input標籤的value中
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“//www.w3.org/TR/html4/loose.dtd”>
<html xmlns:th=”//www.thymeleaf.org”>
<head>
<title>標題</title>
</head>
<body>
<span th:text=”標題“></span>
<hr/>
<span th:text=”${msg}”></span>
<hr/>
<input th:value=”${msg}”>
</body>
</html>
四、Thymeleaf的內置對象及表達式
Thymeleaf提供了一些內置對象,內置對象可直接在模板中使用。這些對象是以#引用
使用內置對象的語法
1.引用內置對象需要使用#
2.大部分內置對象的名稱都以s結尾。如: strings、 numbers、 dates
${#strings. isEmpty(key)}
判斷字元串是否為空,如果為空返回true,否則返回false
${#strings . contains(msg, ‘T’)}
判斷字元串是否包含指定的子串,如果包含返回true,否則返回false
${#strings. startsWith(msg, ‘a’)}
判斷當前字元串是否以子串開頭,如果是返回true,否則返回false
從零開始的Spring Boot(6、Thymeleaf內置對象及表達式大全)
//www.cnblogs.com/gaolight/p/13138087.html
五、Thymeleaf的條件判斷
th:if
條件判斷
th:switch / th:case ;
th:switch / th:case與Java 中的switch 語句等效,有條件地顯示匹配的內容。如果有
多個匹配結果只選擇第– –個 顯示。
th:case= =”*”表示Java中switch的default,即沒有case的值為true時則顯示th:case= =”*”
的內容。
六、Thymeleaf的迭代遍歷
th:each
迭代器,用於循環迭代集合
th:each 狀態變數
1) index:當前迭代器的索引從0開始
2) count:當 前迭代對象的計數從1開始
3) size:被迭代對象的長度
4) odd/even:布爾值, 當前循環是否是偶數/奇數從0開始
5) first:布爾值,當前循環的是否是第一條,如果是返回true否則返回false
6) last:布爾值,當前循環的是否是最後一條,如果是則返回true否則返回false
迭代Map
七、Thymeleaf的常見配置