近日 在springboot項目中使用thymeleaf時,莫名報了以下錯誤:
在網上查找文章明白了報錯的原因,這是由于如果使用thymeleaf 為模板,那么解析時就要求html必須為嚴格的html5格式,即必須有完整的結束標記, 不然就會報錯。
在html頁面中,諸如input,meta,link等標簽 ,是可以不用閉合就可以被解析的(自閉合的),但是由于這里嚴格要求html5格式
于是解決辦法如下:
1) 在報錯的標簽上加入 結束標簽。
2) 修改為不嚴格的模式。
在配置文件中加入如下配置:
mode: LEGACYHTML5
使用該配置,需要加入以下依賴:
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
3) 修改高版本的thymeleaf版本 。
低版本(即spring-boot-starter-parent的版本) SpringBoot 默認使用的thymeleaf 版本為 2.1版本 ,該版本無法識別html5中常見的自閉合標簽。官方原話,可以使用高版本thymeleaf,并通過配置來解決該問題。
可以在pom文件中強行指定thymeleaf的版本 ,如下:
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
然后再配置文件中配置如下:
thymeleaf: mode: HTML
事實上,我在使用高版本的springBoot版本(2.0.4.RELEASE)時,并沒有遇到這個情況 ,而該項目中使用的是1.5.9版本的springboot ,這也從側面證明該方法可行。
Springboot 集成 Thymeleaf 及常見錯誤
Thymeleaf模板引擎是springboot中默認配置,與freemarker相似,可以完全取代jsp,在springboot中,它的默認路徑是src/main/resources/templates 靜態文件css, js 等文件默認路徑是src/main/resources/static,所有項目中如果沒有這個目錄需要手動加上了
首先我們要在pom.xml文件中添加依賴
<!-- thymeleaf 模板引用 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
引用之后我們就來測試一下, 在pom.xml中引入依賴之后。你完全可以不用配置(也秉承了springboot 約定優于配置)當然你如果需要自定義一些屬性,你可以在application.properties 中添加配置。
測試類@Controller
/** * @author pillarzhang * @date 2019-06-03 */ @Controller public class loginController { @RequestMapping("/index") public String index(){ return "index"; } }
Index,html 頁面如下
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Insert title here</title> </head> <body> <p style="color:red">hello world</p> </body> </html>
啟動項目,輸入http://localhost:8081/index 即可看到如下頁面
這就成功的集成了Thymeleaf。
注意:前面也說了,如果你不配置任何屬性依然可以使用,當然你也可以自己設置,在配置文件中application.properties 設置相應的屬性
spring.thymeleaf.prefix=classpath:/templates/ 設置thymeleaf路徑默認為src/main/resources/templates spring.thymeleaf.suffix=.html 設置thymeleaf模板后綴 spring.thymeleaf.content-type=text/html spring.thymeleaf.cache=false 是否開啟緩存默認為true spring.thymeleaf.mode=LEGACYHTML5 設置thymeleaf嚴格校驗 spring.thymeleaf.encoding=UTF-8 設置編碼
1、配置完成之后一定要注意路徑地址是否正確,
2、一定要用@Controller,如果使用@RestController,有可能返回return中的一串字符
3、方法前不要加@ResponseBody,加這個注釋相當于@RestController, 返回一串字符串同上
4、如果載application.properties重配置屬性,一定要注意是否書寫有誤,不能多空格否則有可能會報如下錯誤:
至此,springboot集成thymeleaf 就完成了,雖然中間遇到了一些小問題,還好解決了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/m0_37564404/article/details/84325432