我是在SpringBoot項目使用Thymeleaf作為模板引擎時報的錯誤
controller代碼非常簡單,如下所示:
@RequestMapping("/abc")
public String hello(Model model) {
model.addAttribute("msg","你好");
return "success";
}
前端success.html也很簡單,代碼如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:text="${msg}">信息</div> </body> </html>
控制台報錯如下:
2019-12-17 11:11:18.333 ERROR 2300 --- [nio-8080-exec-3] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-3] Exception processing template "success": Exception parsing document: template="success", line 6 - column 3 2019-12-17 11:11:18.335 ERROR 2300 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Exception parsing document: template="success", line 6 - column 3] with root cause org.xml.sax.SAXParseException: 元素類型 "meta" 必須由匹配的結束標記 "</meta>" 終止。 at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_161] at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177) ~[na:1.8.0_161] at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400) ~[na:1.8.0_161]
前端報錯如圖:

通過console控制台的【Exception parsing document: template="success", line 6 - column 3]】報錯可以看出,thymeleaf在解析success.html的第六行時發生了錯誤。報錯原因控制台也列出來了,即: 元素類型 "meta" 必須由匹配的結束標記 "</meta>" 終止。
解決方法一
解決方法之一,就是我們將success.html文件的meta標簽添加封閉符號,即加上斜杠即可,如下圖:

結果:

解決辦法二
在spring中使用thymeleaf的時候,會對html進行嚴格的語法校驗,比如在本例中,頁面html缺少了封閉符號/,就會報錯而轉到錯誤頁。這實際並沒有什么必要。因此,在第二種解決方法中,我們可以設置使得thymeleaf對html非嚴格檢查。
1)在maven中添加依賴
<!--引入NekoHTML,配合spring.thymeleaf.mode=LEGACYHTML5使用,使Thymeleaf 可以解析非嚴格html格式的文檔--> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
2)在application.properties全局配置文件中加入如下配置
spring.thymeleaf.mode=LEGACYHTML5
注:默認spring.thymeleaf.mode=HTML5,是嚴格檢查 。LEGACYHTML5需要搭配NekoHTML庫才可用,實現thymeleaf非嚴格檢查。
解決方法3
在我的例子中,默認使用的是2.1.6版本的thymeleaf

通過thymeleaf3官方文檔,得知可以用以下方法來修改thymeleaf版本,即在pom的properties標簽加入如下配置
<properties> <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 --> <!-- thymeleaf2 layout1--> <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version> </properties>
在更新thymeleaf版本到3以上之后,就不會因為缺少結束標簽而報錯了。
