第一步:在Maven中引入thymeleaf的依賴,加入如下代碼便可引入須要的Jar包。html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
第二步:而後在你的HTML頁面的<html>元素中須要加入如下屬性html5
<html xmlns:th="http://www.thymeleaf.org">
第三步:在application.yml中對thymeleaf進行配置( properties配置也同樣,若是不清楚Spring Boot中yml及 properties 配置文件是幹什麼的,請看我Spring Boot系列的博客)java
#mode: 去掉html的校驗。 cache: 關閉thymeleaf的緩存 thymeleaf: cache: false mode: LEGACYHTML5
若是你是使用標準路徑的話,視圖解析器的配置能夠省略,若是你的頁面沒放入ClassPath路徑的話,請看最後的thymeleaf在SpringBoot中配置詳解大全。spring
第四步:寫一個Controllar去映射到你的頁面(和SpringMVC基本一致)緩存
//登陸 @RequestMapping("/login") public String login(){ //return 中就是你頁面的名字(不帶.html) return "login"; }
第五步:你就能夠興高采烈的去訪問你的頁面了,可是當我訪問的時候卻出現瞭如下的錯誤。springboot
你若是在網上去百度的話,全部的博客都說Maven只須要引入以上一個依賴就可使用thymeleaf,而我當時遇到這個錯誤的時候更是一臉懵逼——臥槽!我是誰?我在哪?這又TM是怎麼了?app
不要慌!仔細的看我截圖報的錯,上面的異常已經說的很清楚了,須要依賴nekoHTML 1.9.15 or newer的版本。 在使用springboot的過程當中,若是使用thymeleaf做爲模板文件,則要求HTML格式必須爲嚴格的html5格式,必須有結束標籤,不然會報錯! 這個錯是由於我在yml中配置,去掉了Html5的校驗,但我並無引入此依賴!(這個錯我也是醉了)在Maven中加入如下依賴便可成功解決。spring-boot
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> </dependency>
再次訪問,Success!!!到此,第一個Thymeleaf的例子就完成了!編碼
接下來附上Thymeleaf在SpringBoot中配置大全。(大全這個是轉的,可是時間過久了我忘記是哪一個博主的了,若是誰知道的話告訴我,我在附加上原創的鏈接)spa
#thymeleaf的配置文件說明 #spring.thymeleaf.cache = true #啓用模板緩存。 #spring.thymeleaf.check-template = true #在呈現模板以前檢查模板是否存在。 #spring.thymeleaf.check-template-location = true #檢查模板位置是否存在。 #spring.thymeleaf.content-type = text / html #Content-Type值。 #spring.thymeleaf.enabled = true #啓用MVC Thymeleaf視圖分辨率。 #spring.thymeleaf.encoding = UTF-8 #模板編碼。 #spring.thymeleaf.excluded-view-names = #應該從解決方案中排除的視圖名稱的逗號分隔列表。 #spring.thymeleaf.mode = HTML5 #應用於模板的模板模式。另請參見StandardTemplateModeHandlers。 #spring.thymeleaf.prefix = classpath:/ templates / #在構建URL時預先查看名稱的前綴。 #spring.thymeleaf.suffix = .html #構建URL時附加到查看名稱的後綴。 #spring.thymeleaf.template-resolver-order = #鏈中模板解析器的順序。 #spring.thymeleaf.view-names = #能夠解析的視圖名稱的逗號分隔列表。/ templates / #在構建URL時先查看名稱的前綴。 #spring.thymeleaf.suffix = .html #構建URL時附加到查看名稱的後綴。 #spring.thymeleaf.template-resolver-order = #鏈中模板解析器的順序。 #spring.thymeleaf.view-names = #能夠解析的視圖名稱的逗號分隔列表。/ templates / #在構建URL時先查看名稱的前綴。 #spring.thymeleaf.suffix = .html #構建URL時附加到查看名稱的後綴。 #spring.thymeleaf.template-resolver-order = #鏈中模板解析器的順序。 #spring.thymeleaf.view-names = #能夠解析的視圖名稱的逗號分隔列表。
原創博客,轉載請註明出處: http://www.javashuo.com/article/p-zlkldpsp-hc.html