thymeleaf簡介
Spring Boot提供了多種模板引擎的默認(rèn)配置支持,但嵌入式容器JSP有限制,2010年后Velocity停止更新,所以這JSP與Velocity兩個不建議使用。而Thymeleaf與SpringMVC的視圖技術(shù),及SpringBoot的自動化配置集成非常完美,幾乎沒有任何成本,你只用關(guān)注Thymeleaf的語法即可。
Thymeleaf的特點(diǎn)
- 動靜結(jié)合:Thymeleaf 在有網(wǎng)絡(luò)和無網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動態(tài)頁面效果。這是由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時會忽略未定義的標(biāo)簽屬性,所以 thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁面時,Thymeleaf 標(biāo)簽會動態(tài)地替換掉靜態(tài)內(nèi)容,使頁面動態(tài)顯示。
- 開箱即用:它提供標(biāo)準(zhǔn)和spring標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn)JSTL、 OGNL表達(dá)式效果,避免每天套模板、該jstl、改標(biāo)簽的困擾。同時開發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。
- 多方言支持:Thymeleaf 提供spring標(biāo)準(zhǔn)方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國際化等功能。
- 與SpringBoot完美整合,SpringBoot提供了Thymeleaf的默認(rèn)配置,并且為Thymeleaf設(shè)置了視圖解析器,我們可以像以前操作jsp一樣來操作Thymeleaf。代碼幾乎沒有任何區(qū)別,就是在模板語法上有區(qū)別。
和SpringBoot整合
- 新建SpringBoot項目(可參考我的上一篇博客SpringBoot初體驗(yàn)),打開pom.xml,添加thymeleaf依賴
<dependencies>
<!--web容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--前端模板thymeleaf依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
- 打開配置文件application,yml(application.properties),關(guān)閉thymeleaf緩存

- 新建HelloWorldController類,返回hello頁面

- templates目錄下新建hello.html

5.打開SpringBootThymeleafApplication類啟動項目

- 瀏覽器中輸入localhost:8080/hello,訪問成功
