大部分屬性和html的一樣,只不過前面加了一個th前綴。
項目名稱:041-springboot-thymeleaf-property
1.創建SpringBoot的web項目并使用模版引擎
2.pom.xml中應該有如下兩個依賴
<!--SpringBoot集成Thymeleaf模版引擎的起步依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--SpringBoot的web項目起步依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.在application.properties中設置thymeleaf參數
#設置thymeleaf頁面緩存失效
spring.thymeleaf.cache=false
#thymeleaf模版前綴,默認值,可選項
spring.thymeleaf.prefix=classpath:/templates/
#thymeleaf模版后綴,默認值,可選項
spring.thymeleaf.suffix=.html
4.創建實體User實體類
在com.abc.springboot.model包下創建User實體類
package com.abc.springboot.model;
/**
* ClassName:User
* Package:com.abc.springboot.model
* Description:
*/
public class User {
private Integer id;
private String nick;
private String phone;
private String address;
//此處省略屬性的set和get
}
5.創建ThymeleafController類
在com.abc.springboot.web包下創建ThymeleafController類
package com.abc.springboot.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* ClassName:ThymeleafController
* Package:com.abc.springboot.web
* Description:
*/
@Controller
public class ThymeleafController {
@RequestMapping(value = "/springboot/thymeleaf/index")
public String index(Model model) {
model.addAttribute("data","哈嘍,SpringBoot");
return "index";
}
}
6.在src/main/resources/templates在創建html頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf'Index</title>
</head>
<body>
<span th:text="${data}"></span>
</body>
</html>
7.測試
定義后臺控制器的路徑,類似標簽的action屬性,主要結合URL表達式,獲取動態變量。
重新BuildModule,瀏覽器訪問瀏覽器訪問http://localhost:8080/08-springboot-thymeleaf/user ,右鍵查看源代碼。
思考:為什么login3中${user.id} 獲取不到數據?
因為我們Thymeleaf是以html為載體的,所以html不會認識${}語法。我們請求的流程是,發送請求給服務器,服務器接收請求后,處理請求,跳轉到指定的靜態html頁面,在服務器端,Thymeleaf模板引擎會按照它的語法,對動態數據進行處理,所以如果要是th開頭,模板引擎能夠識別,會在服務器端進行處理,獲取數據;如果沒有以th開頭,那么Thymeleaf模板引擎不會處理,直接返回給客戶端了。
設置請求方法
<form id="login" th:action="@{/login}" th:method="post">......</form>
th:href
定義超鏈接,主要結合URL表達式,獲取動態變量
<h1>th:href使用</h1>
<a >超鏈接百度</a><br/>
<a th:href="'http://www.baidu.com?id=' + ${user.id}">th:href鏈接</a>
th:src
用于外部資源引入,比如<script>標簽的src屬性,<img>標簽的src屬性,常與@{}表達式結合使用,在SpringBoot項目的靜態資源都放到resources的static目錄下放到static路徑下的內容,寫路徑時不需要寫上static
<h1>th:src使用</h1>
<script src="/static/js/jquery-1.7.2.min.js"></script>
<script th:src="@{/js/jquery-1.7.2.min.js}"></script>
<img th:src="@{/img/alipay.jpg}">
<script>
$(function () {
alert("=====");
});
</script>
這種方式比傳統方式的好處是,在URL表達式前加/,會自動加上上下文根,避免404找不到資源的情況。
類似html標簽中的id屬性
<span th:id="${hello}">aaa</span>
th:name
設置名稱
<input th:type="text" th:id="userName" th:name="userName">
th:value
類似html標簽中的value屬性,能對某元素的value屬性進行賦值
<input type="hidden" id="userId" name="userId" th:value="${userId}">
th:attr
該屬性也是用于給HTML中某元素的某屬性賦值,但該方式寫法不夠優雅;
比如上面的例子可以寫成如下形式
<input type="hidden" id="userId" name="userId" th:attr="value=${userId}" >
好處是可以給html中沒有定義的屬性動態的賦值
<!--thymeleaf沒有對應的th標簽,所以${user.id}不能被識別-->
<span zhangsan=${user.id}></span>
<!--通過th:attr對自定義的屬性賦值-->
<span th:attr="zhangsan=${user.id}"></span>
th:text
用于文本的顯示,該屬性顯示的文本在標簽體中,如果是文本框,數據會在文本框外顯示,要想顯示在文本框內,使用th:value
<input type="text" id="realName" name="reaName" th:text="${realName}">
th:object
用于數據對象綁定
通常用于選擇變量表達式(星號表達式)
點擊事件,th:onclick="'getCollect()'"
設置樣式
<a th:onclick="'fun1('+${user.id}+')'" th:style="'color:red'">點擊我</a>
th:each
這個屬性非常常用,比如從后臺傳來一個對象集合那么就可以使用此屬性遍歷輸出,它與JSTL中的類似,此屬性既可以循環遍歷集合,也可以循環遍歷數組及Map
1.遍歷List集合
在ThymeleafController中添加eachList方法,準備集合數據
@RequestMapping("/each/list")
public String eachList(Model model){
List<User> userList = new ArrayList<User>();
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";
}
創建each.html對List集合進行遍歷
<h1>th:each遍歷List集合</h1>
<div th:each="user,userStat:${userList}">
<span th:text="${userStat.index}"></span>
<span th:text="${user.id}"></span>
<span th:text="${user.phone}"></span>
<span th:text="${user.nick}"></span>
<span th:text="${user.address}"></span><br/>
</div>
代碼說明
th:each="user, iterStat : ${userlist}"中的 ${userList} 是后臺傳過來的集合
• user
定義變量,去接收遍歷${userList}集合中的一個數據
• iterStat
${userList} 循環體的信息
• 其中user及iterStat自己可以隨便取名
• interStat是循環體的信息,通過該變量可以獲取如下信息
index: 當前迭代對象的index(從0開始計算)
count: 當前迭代對象的個數(從1開始計算)這兩個用的較多
size: 被迭代對象的大小
current: 當前迭代變量
even/odd: 布爾值,當前循環是否是偶數/奇數(從0開始計算)
first: 布爾值,當前循環是否是第一個
last: 布爾值,當前循環是否是最后一個
注意:循環體信息interStat也可以不定義,則默認采用迭代變量加上Stat后綴,即userStat
• 瀏覽器訪問測試
2.遍歷Map集合
在ThymeleafController中的each方法中準備Map集合數據
@RequestMapping(value = "/each/map")
public String eachMap(Model model) {
Map<Integer,Object> userMap = new HashMap<Integer, Object>();
for (int i = 0;i < 10;i++){
User user = new User();
user.setId(100+i);
user.setNick("張" + i);
user.setPhone("1370000000" + i);
user.setAddress("北京市大興區" + i);
userMap.put(i,user);
}
model.addAttribute("userMap",userMap);
return "each";
}
在each.html頁面對Map集合進行遍歷
<h1>th:each遍歷Map集合</h1>
<div th:each="map:${userMap}">
<span th:text="${map.key}"></span>
<span th:text="${map.value}"></span>
<span th:text="${map.value.id}"></span>
<span th:text="${map.value.phone}"></span>
<span th:text="${map.value.nick}"></span>
<span th:text="${map.value.address}"></span>
</div>
代碼說明
th:each="map:${userMap}"
用map接收每次遍歷的結果,封裝為一個鍵值對map.key獲取當前鍵值對中的key map.value獲取當前鍵值對中的value
瀏覽器訪問測試
3.遍歷Array數組
在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(100+i);
user.setNick("張" + i);
user.setPhone("1370000000" + i);
user.setAddress("北京市大興區" + i);
userArray[i]=user;
}
model.addAttribute("userArray",userArray);
return "each";
}
在each.html頁面對數組進行遍歷(和List一樣)
<h1>th:each遍歷Array數據集合</h1>
<div th:each="user,userStat:${userArray}">
<span th:text="${userStat.count}"></span>
<span th:text="${user.id}"></span>
<span th:text="${user.phone}"></span>
<span th:text="${user.nick}"></span>
<span th:text="${user.address}"></span>
</div>
瀏覽器訪問測試
4.比較復雜的循環案例
需求:List里面放Map,Map里面又放的是List
在ThymeleafController的each方法中構造數據
@RequestMapping(value = "/each/all")
public String all(Model model) {
//構造復雜的數據關系 List->Map->List->User
List<Map<Integer,List<User>>> myList = new ArrayList<Map<Integer,List<User>>>();
for(int n = 0 ; n < 2;n ++){
Map<Integer,List<User>> myMap = new HashMap<Integer,List<User>>();
for(int m = 0 ;m < 2; m ++){
List<User> myList1 = new ArrayList<User>();
for(int i = 0 ;i < 3; i++){
User user = new User();
user.setId(i);
user.setNick("張" + i);
user.setPhone("1361234567" + i);
user.setAddress("北京市大興區" + i);
myList1.add(user);
}
myMap.put(m,myList1);
}
myList.add(myMap);
}
model.addAttribute("myList",myList);
return "each";
}
在each.html頁面對復雜集合關系進行遍歷
<h1>遍歷復雜的集合:List -> Map -> List -> User</h1>
<!--首先遍歷List,獲取Map-->
<span th:each="myMap,listStat:${myList}">
<!--再次遍歷Map,獲取List-->
<span th:each="myKeyValue:${myMap}">
<!--獲取當前Map集合的Id-->
<span th:text="${myKeyValue.key}"></span>
<span th:each="user,listSate:${myKeyValue.value}">
<span th:text="${user.id}"></span>
<span th:text="${user.phone}"></span>
<span th:text="${user.nick}"></span>
<span th:text="${user.address}"></span>
<br/>
</span>
</span>
</span>
瀏覽器訪問測試
向ThymeleafController中添加condition方法中,通過model傳遞sex值為1
@RequestMapping(value = "/condition")
public String condition(Model model) {
model.addAttribute("sex",1);
return "condition";
}
創建condition.html頁面
① th:if
在condition.html頁面進行條件判斷
<div style="color: red">th:if條件判斷:如果滿足條件,顯示標簽,如果不滿足條件,標簽就不顯示</div>
<!--th:if條件判斷:如果滿足條件,顯示標簽,如果不滿足條件,標簽就不顯示-->
<span th:if="${sex == 1}">
男:<input type="radio" name="sex" th:value="男"/>
</span>
<span th:if="${sex == 2}">
女:<input type="radio" name="sex" th:value="女"/>
</span>
② th:unless(了解)
th:unless是th:if的一個相反操作
<!--th:unless是th:if的相反操作,即對判斷條件取反,一般我們用th:if-->
<span th:unless="${sex == 1}">
男:<input type="radio" name="sex" th:value="男"/>
</span>
<span th:unless="${sex == 2}">
女:<input type="radio" name="sex" th:value="女"/>
</span>
③ th:switch/th:case
switch,case判斷語句
<div th:switch="${sex}">
<p th:case="1">性別:男</p>
<p th:case="2">性別:女</p>
<p th:case="*">性別:未知</p>
</div>
一旦某個case判斷值為true,剩余的case則都當做false,“*”表示默認的case,前面的case都不匹配時候,執行默認的case
④ 瀏覽器訪問測試
th:inline 有三個取值類型 (text, javascript 和 none)
1.內斂文本(th:inline=”text”)
可以讓Thymeleaf表達式不依賴于html標簽,直接使用內斂表達式[[表達式]]即可獲取動態數據,要求在父級標簽上加th:inline = “text”屬性
在user.html頁面上,加如下代碼
!--內斂文本-->
標準變量表達式用戶數據的展示:<br>
<span th:text="${user.id}"></span>
<span th:text="${user.nick}"></span>
<span th:text="${user.phone}"></span>
<span th:text="${user.address}"></span>
<br>
<!--以上代碼可以使用內斂文本代替-->
內斂表達式 用戶數據的展示:<br>
<span th:inline="text">
[[${user.id}]]
[[${user.nick}]]
[[${user.phone}]]
[[${user.address}]]
</span>
<br>
瀏覽器訪問測試
注意:一般我們將放到標簽中
2.內斂腳本(th:inline=”javascript”)
在js代碼中獲取后臺的動態數據
在user.html頁面上,加如下代碼
<button type ="button" onclick="func()">抽獎</button>
<script type="text/javascript" th:inline="javascript">
function func(){
alert("恭喜" + [[${user.nick}]] +"手機號為"+[[${user.phone}]]+"中獎!");
}
</script>
瀏覽器訪問測試