在學習使用springBoot時,一直傳回的是json資料,這對ajax的異步互動是非常友善的。但是此前使用springMVC時,controller中的傳回值有傳回的是一個視圖,或者這個視圖被定義在ModelAndView對象中傳回的,這樣就可以通過視圖解析器在用戶端顯示的是一個頁面,而不是一串json資料,個人就覺得,springboot一定是可以這樣實作的,不然這個架構自然不是一個完整的,也得不到廣泛的使用。那麼,猛然想起來,springboot本就自動使用的是springMVC作為控制層的架構,那麼,就可以使用像此前springMVC一樣對是視圖的解析方式并且傳回用戶端。 最近接觸到thymeleaf,一個非常優秀的頁面模闆架構,由于沒有更多的了解,查閱資料是以轉載一篇作為個人筆記
原創位址:http://blog.csdn.net/u012706811/article/details/52185345 非常感謝這位前輩的分享
轉載内容:
因為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-
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="@{http://blog.csdn.net/u012706811}">絕對路徑</a>
<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}" target="_blank" rel="external nofollow" 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 :)
*/
${#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遇到問題再加上去
參考連結: http://www.tianmaying.com/tutorial/using-thymeleaf
整合項目位址:
https://github.com/nl101531/JavaWEB
補充
在spring-boot1.4之後,支援thymeleaf3,可以更改版本号來進行修改支援.
3相比2極大的提高了效率,并且不需要标簽閉合,類似的link,img等都有了很好的支援,按照如下配置即可
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- set thymeleaf version -->
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
<!--set java version-->
<java.version>1.8</java.version>
</properties>