Thymeleaf 集成spring

 

如需先了解Thymeleaf的單獨使用,請參考《Thymeleaf模板引擎使用》一文。html

依賴的jar

Thymeleaf 已經集成了spring3.x4.x版本,所以須要在項目的classpath路徑下加入thymeleaf- spring3- {version}.jar thymeleaf- spring4- {version}.jarjava

配置Thymeleaf模板解析器與spring模板引擎

要將Thymeleaf 整合到spring中,只需將模板解析器實例和模板引擎實例以bean的方式配置到spring的配置文件中,讓spring 容器自動管理模板解析器實例和模板引擎實例,和手動代碼建立模板解析器實例和模板引擎實例原理是同樣的。以下:web

 

和手動代碼建立解析器同樣,須要經過模板解析器設置前置,後綴,模板節點。同理,注入解析器建立模板引擎。注意這裏的模板解析器是整合了spring的模板引擎spring

org.thymeleaf.spring4.SpringTemplateEnginemvc

而不是org.thymeleaf.TemplateEngine.TemplateEngine。eclipse

更多關於模板解析器與模板引擎的建立詳見「Thymeleaf模板引擎使用」一文。網站

視圖以及視圖解析器

View接口一般經過一些模板引擎的執行像JSP(Thymeleaf)控制着實際的html頁面的渲染。視圖模型頁面容許咱們經過定義成beans的方式修改和預約義頁面行爲。ViewResolvers針對具體的操做和語言環境獲取視圖對象。一般狀況下,控制器要求ViewResolvers經過一個特定的視圖名稱(控制器方法返回的一個字符串)去轉發一個視圖,而後應用中的全部視圖解析器以執行鏈的方式執行,直到有一個能解析這個視圖爲止,在這種狀況下,一個View對象被返回,並傳遞控制流程從新渲染html頁面。spa

springmvc有兩個接口支持着核心模板系統,他們是:3d

org. springframework. web. servlet. Viewhtm

org. springframework. web. servlet. ViewResolver

Thymeleaf中支持着核心模板系統的接口是:

org. thymeleaf. spring4. view. ThymeleafView

org. thymeleaf. spring4. view. ThymeleafViewResolver

spring的配置文件中配置thymeleaf視圖解析器以下:

OKthymeleaf整合spring的基本配置完成了。SpringMVC的配置只需在spring的配置文件中配置自動掃描包便可。

 

更多可選配置請訪問官方網站http://www.thymeleaf.org/

 

實例演示

主頁面home.html

 

控制器

返回成功頁面success.html

 

Thymeleaf經過「th:object」屬性將整個表單綁定到命令對象(beanpassengerReqBean,經過「th: field」屬性將表單屬性綁定到命令對象的屬性須要注意的是,命令對象的指定必須使用表達式「${}」,且沒有屬性導航,也就是說th:object="${passengerReqBean.firstName}"是無效的。運行結果

 

更多表單元素的綁定請訪問官方網站http://www.thymeleaf.org/

相關文章
相關標籤/搜索