自從來公司後都沒用過jsp當界面渲染了,因爲前後端分離不是很好,反而模板引擎用的比較多,thymeleaf最大的優勢後綴爲html,就是只需要瀏覽器就可以展現頁面了,還有就是thymeleaf可以很好的和spring集成.下面開始學習.
1.引入依賴
maven中直接引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
可以查看依賴關係,發現spring-boot-starter-thymeleaf下面已經包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依賴去掉.
2.配置視圖解析器
spring-boot很多配置都有默認配置,比如默認頁面映射路徑爲
classpath:/templates/*.html
同樣靜態文件路徑爲
classpath:/static/
在application.properties中可以配置thymeleaf模板解析器屬性.就像使用springMVC的JSP解析器配置一樣
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html#開發時關閉緩存,不然沒法看到實時頁面
spring.thymeleaf.cache=false
#thymeleaf end
具體可以配置的參數可以查看
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
這個類,上面的配置實際上就是注入到該類中的屬性值.
3.編寫DEMO
1.控制器
@Controller
public class HelloController {
private Logger logger = LoggerFactory.getLogger(HelloController.class); /**
* 測試hello
* @return
*/
@RequestMapping(value = "/hello",method = RequestMethod.GET) public String hello(Model model) {
model.addAttribute("name", "Dear"); return "hello";
}
}
2.view(註釋爲IDEA生成的索引,便於IDEA補全)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
</body>
</html>
3.效果
4.基礎語法
回味上面的DEMO,可以看出來首先要在改寫html標籤
<html xmlns:th="http://www.thymeleaf.org">
這樣的話纔可以在其他標籤裏面使用th:*
這樣的語法.這是下面語法的前提.
1.獲取變量值
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
可以看出獲取變量值用$
符號,對於javaBean的話使用變量名.屬性名
方式獲取,這點和EL表達式一樣.
另外$
表達式只能寫在th標籤內部,不然不會生效,上面例子就是使用th:text
標籤的值替換p
標籤裏面的值,至於p裏面的原有的值只是爲了給前端開發時做展示用的.這樣的話很好的做到了前後端分離.
2.引入URL
Thymeleaf對於URL的處理是通過語法@{…}來處理的
<a th:href="@{
<a th:href="@{/}">相對路徑</a>
<a th:href="@{css/bootstrap.min.css}">Content路徑,默認訪問static下的css文件夾</a>
類似的標籤有:th:href
和th:src
3.字符串替換
很多時候可能我們只需要對一大段文字中的某一處地方進行替換,可以通過字符串拼接操作完成:
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
一種更簡潔的方式是:
<span th:text="|Welcome to our application, ${user.name}!|">
當然這種形式限制比較多,|…|中只能包含變量表達式${…},不能包含其他常量、條件表達式等。
4.運算符
在表達式中可以使用各類算術運算符,例如+, -, *, /, %
th:with="isEven=(${prodStat.count} % 2 == 0)"
邏輯運算符>, <, <=,>=,==,!=都可以使用,唯一需要注意的是使用<,>時需要用它的HTML轉義符:
th:if="${prodStat.count} > 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
5.條件
if/unless
Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,標籤只有在th:if中條件成立時才顯示:
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:unless於th:if恰好相反,只有表達式中的條件不成立,纔會顯示其內容。
Switch
Thymeleaf同樣支持多路選擇Switch結構:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
默認屬性default可以用*表示:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p></div>
6.循環
渲染列表數據是一種非常常見的場景,例如現在有n條記錄需要渲染成一個表格
,該數據集合必須是可以遍歷的,使用th:each標籤:
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p>
<a href="../home.html" th:href="@{/}">Return to home</a>
</p></body>
可以看到,需要在被循環渲染的元素(這裏是)中加入th:each標籤,其中th:each=”prod : ${prods}”意味着對集合變量prods進行遍歷,循環變量是prod在循環體中可以通過表達式訪問。
7.Utilities
爲了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置於Context中),可以通過#直接訪問:
#dates
#calendars
#numbers
#strings
arrays
lists
sets
maps
…
下面用一段代碼來舉例一些常用的方法:
date
/*
* Format date with the specified pattern
* Also works with arrays, lists or sets
*/
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}/*
* Create a date (java.util.Date) object for the current date and time
*/
${#dates.createNow()}/*
* Create a date (java.util.Date) object for the current date (time set to 00:00)
*/
${#dates.createToday()}
string
/*
* Check whether a String is empty (or null). Performs a trim() operation before check
* Also works with arrays, lists or sets
*/${#strings.isEmpty(name)}${#strings.arrayIsEmpty(nameArr)}${#strings.listIsEmpty(nameList)}${#strings.setIsEmpty(nameSet)}
/*
* Check whether a String starts or ends with a fragment
* Also works with arrays, lists or sets
*/${#strings.startsWith(name,'Don')} // also array*, list* and set*${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
/*
* Compute length
* Also works with arrays, lists or sets
*/${#strings.length(str)}
/*
* Null-safe comparison and concatenation
*/${#strings.equals(str)}${#strings.equalsIgnoreCase(str)}${#strings.concat(str)}${#strings.concatReplaceNulls(str)}
/*
* Random
*/${#strings.randomAlphanumeric(count)}
快速的學習還是直接寫例子最快,後期寫Demo遇到問題再加上去