開發與維運

SpringBoot整合Thymeleaf | 帶你讀《SpringBoot實戰教程》之十七

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《SpringBoot實戰教程》,主講人楊紅豔,點擊查看視頻內容

24. SpringBoot整合Thymeleaf

SpringBoot官方是不推薦jsp頁面的,推薦的是模板引擎。Thymeleaf是其中一種模板引擎,下面我們看一下SpringBoot如何整合Thymeleaf?
首先要進行依賴:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>

我們把這個依賴放入工程中:
image.png
接下來構建一下數據:
image.png

啟動之後的結果為:
image.png
我們需要將下列屬性放入全局配置中:

springboot整合thymeleaf

spring.thymeleaf.cache=false

檢查模板是否存在,然後再呈現

spring.thymeleaf.check-template-location=true

Content-Type值

spring.thymeleaf.content-type=text/html

啟用MVC Thymeleaf視圖分辨率

spring.thymeleaf.enabled=true

應該從解決方案中排除的視圖名稱的逗號分隔列表

spring.thymeleaf.excluded-view-names=

模板編碼

spring.thymeleaf.mode=LEGACYHTML5

在構建URL時預先查看名稱的前綴

spring.thymeleaf.prefix=classpath:/templates/

構建URL時附加查看名稱的後綴.

spring.thymeleaf.suffix=.html

鏈中模板解析器的順序

spring.thymeleaf.template-resolver-order= o

可以解析的視圖名稱的逗號分隔列表

spring.thymeleaf.view-names=

thymeleaf end

即聲明thymeleaf使用非嚴 格的html。啟動之後訪問頁面會報如下錯誤:
org.thymeleaf.exceptions.ConfigurationException: Cannot perform conversion to XML from legacy HTML: The nekoHTML library is not in classpath. nekoHTML 1.9.15 or newer is required for processing templates in "LEGACYHTML5" mode [http://nekohtml.sourceforge.net]. Maven spec: "net.sourceforge.nekohtml::nekohtml::1.9.15". IMPORTANT: DO NOT use versions of nekoHTML older than 1.9.15.
• 1

我們需要創建全局配置文件:
image.png

以上的屬性指定了模板的格式
image.png
重新啟動的結果為:
image.png
控制檯顯示為配置錯誤:
image.png

上面的異常已經說的很清楚了,需要依賴nekoHTML 1.9.15 or newer的版本。maven依賴如下

<dependency>
        <groupId>net.sourceforge.nekohtml</groupId>
        <artifactId>nekohtml</artifactId>
        <version>1.9.22</version>
</dependency>

就取到值了,最後的結果為:
image.png

Leave a Reply

Your email address will not be published. Required fields are marked *