如需先了解Thymeleaf的單獨使用,請參考《Thymeleaf模板引擎使用》一文。
依賴的jar包
Thymeleaf 已經集成了spring的3.x,4.x版本,因此需要在項目的classpath路徑下加入thymeleaf- spring3- {version}.jar 或thymeleaf- spring4- {version}.jar。
配置Thymeleaf模板解析器與spring模板引擎
要將Thymeleaf 整合到spring中,只需將模板解析器實例和模板引擎實例以bean的方式配置到spring的配置文件中,讓spring 容器自動管理模板解析器實例和模板引擎實例,和手動代碼創建模板解析器實例和模板引擎實例原理是一樣的。如下:
和手動代碼創建解析器一樣,需要通過模板解析器設置前置,后綴,模板節點。同理,注入解析器創建模板引擎。注意這里的模板解析器是整合了spring的模板引擎
org.thymeleaf.spring4.SpringTemplateEngine,
而不是org.thymeleaf.TemplateEngine.TemplateEngine。
更多關於模板解析器與模板引擎的創建詳見“Thymeleaf模板引擎使用”一文。
視圖以及視圖解析器
View接口通常通過一些模板引擎的執行像JSP(或Thymeleaf)控制着實際的html頁面的渲染。視圖模型頁面允許我們通過定義成beans的方式修改和預定義頁面行為。ViewResolvers針對具體的操作和語言環境獲取視圖對象。通常情況下,控制器要求ViewResolvers通過一個特定的視圖名稱(控制器方法返回的一個字符串)去轉發一個視圖,然后應用中的所有視圖解析器以執行鏈的方式執行,直到有一個能解析這個視圖為止,在這種情況下,一個View對象被返回,並傳遞控制流程重新渲染html頁面。
springmvc有兩個接口支持着核心模板系統,他們是:
org. springframework. web. servlet. View
org. springframework. web. servlet. ViewResolver
而Thymeleaf中支持着核心模板系統的接口是:
org. thymeleaf. spring4. view. ThymeleafView
org. thymeleaf. spring4. view. ThymeleafViewResolver
在spring的配置文件中配置thymeleaf視圖解析器如下:
OK,thymeleaf整合spring的基本配置完成了。SpringMVC的配置只需在spring的配置文件中配置自動掃描包即可。
更多可選配置請訪問官方網站http://www.thymeleaf.org/。
實例演示
主頁面home.html
控制器
返回成功頁面success.html
Thymeleaf通過“th:object”屬性將整個表單綁定到命令對象(bean)passengerReqBean,通過“th: field”屬性將表單屬性綁定到命令對象的屬性。需要注意的是,命令對象的指定必須使用表達式“${}”,且沒有屬性導航,也就是說th:object="${passengerReqBean.firstName}"是無效的。運行結果
更多表單元素的綁定請訪問官方網站http://www.thymeleaf.org/。