本項目的筆記和資料的Download,請點擊這一句話自行獲取。css
day01-springboot(理論篇) ;day01-springboot(實踐篇) ;day01-springboot(Thymeleaf快速入門)html
SpringBoot不推薦使用jsp,可是支持一些模板引擎技術:spring
簡單說, Thymeleaf 是一個模板引擎,它能夠徹底替代 JSP 。相較於其餘的模板引擎,它有以下四個極吸引人的特色:瀏覽器
接下來,咱們就經過入門案例來體會Thymeleaf的魅力:緩存
編寫一個controller方法,返回一些用戶數據,放入模型中,未來在頁面渲染springboot
@GetMapping("/all") public String all(ModelMap model) { // 查詢用戶 List<User> users = this.userService.queryAll(); // 放入模型 model.addAttribute("users", users); // 返回模板名稱(就是classpath:/templates/目錄下的html文件名) return "users"; }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
SpringBoot會自動爲Thymeleaf註冊一個視圖解析器:服務器
與解析JSP的InternalViewResolver相似,Thymeleaf也會根據前綴和後綴來肯定模板文件的位置:網絡
classpath:/templates/
.html
因此若是咱們返回視圖:users
,會指向到 classpath:/templates/users.html
併發
通常咱們無需進行修改,默認便可。
根據上面的介紹,模板默認放在classpath下的templates文件夾,咱們新建一個html文件放入其中:
編寫html模板,渲染模型中的數據:
注意,把html 的名稱空間,改爲:xmlns:th="http://www.thymeleaf.org"
會有語法提示。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首頁</title> <style type="text/css"> table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto} table, th, td {border: 1px solid darkslategray;padding: 10px} </style> </head> <body> <div style="text-align: center"> <span style="color: darkslategray; font-size: 30px">歡迎光臨!</span> <hr/> <table class="list"> <tr> <th>id</th> <th>姓名</th> <th>用戶名</th> <th>年齡</th> <th>性別</th> <th>生日</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}">1</td> <td th:text="${user.name}">張三</td> <td th:text="${user.userName}">zhangsan</td> <td th:text="${user.age}">20</td> <td th:text="${user.sex}">男</td> <td th:text="${user.birthday}">1980-02-30</td> </tr> </table> </div> </body> </html>
咱們看到這裏使用瞭如下語法:
${}
:這個相似與el表達式,但實際上是ognl的語法,比el表達式更增強大th-
指令:th-
是利用了Html5中的自定義屬性來實現的。若是不支持H5,能夠用data-th-
來代替
th:each
:相似於c:foreach
遍歷集合,可是語法更加簡潔th:text
:聲明標籤中的文本
<td th-text='${user.id}'>1</td>
,若是user.id有值,會覆蓋默認的1接下來,咱們打開頁面測試一下:
Thymeleaf會在第一次對模板解析以後進行緩存,極大的提升了併發處理能力。可是這給咱們開發帶來了不便,修改頁面後並不會馬上看到效果,咱們開發階段能夠關掉緩存使用:
# 開發階段關閉thymeleaf的模板緩存 spring.thymeleaf.cache=false
在Idea中,咱們須要在修改頁面後按快捷鍵:`Ctrl + Shift + F9` 對項目進行rebuild才能夠。
============================
參考資料:
end