Spring Boot使用thymeleaf 解析html template时失败

       Spring Boot启动成功,访问相应页面报错,看log是java解析html某个标签失败,但是关键的报错信息在Intellij terminal下显示的是乱码.....觉着应该是使用thymeleaf时哪里出了问题。最后在简书找到一篇文章,原文如下:

 

Spring Boot项目的默认模板引擎是Thymeleaf,这没什么好说的,个人觉得也非常好,因为这款引擎可以前后端同时开发,类似th:xxx这样的内联标签属性会被html5无情忽视,所以前台在开发静态页面的时候就正常开发,正常预览,后台拿来开发好的模板加上这个标签分分钟就开始用,这也是这个引擎的最大好处(你把后台jsp页面在浏览器直接打开就知道这是什么意思了)。bootstrap作为老牌前台框架,有大量开发好的优秀模板(尤其是各种admin模板),拿来就能用。但是最近在试图把网上下载的一套开源bootstrap模板整合到thymeleaf时遇到一些小问题,经过查阅资料最后解决了,记录一下。

这个问题就是,当你把前台模板直接copy到工程中(css/js/img等直接放在resources/static文件夹下,页面放在resources/templates下),类似这样:

login.html中加一句话变成thymeleaf模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
...

这时你直接访问这个login.html会报错。
查阅官方文档得知原因:springboot默认使用 Thymeleaf 2.1版本,这个版本无法识别html5中常见的自闭合标签,如<input type="text" />。好弱的感觉。
解决办法时强制更换到Thymeleaf 3:在pom.xml中添加属性:

<properties>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

然后在application.properties中添加以下一句:
spring.thymeleaf.mode: HTML
注意这一句是必须要加的,需要显式指定。
以下是官方原话:

By default, spring-boot-starter-thymeleaf
uses Thymeleaf 2.1. If you are using the spring-boot-starter-parent
, you can use Thymeleaf 3 by overriding thethymeleaf.version
and thymeleaf-layout-dialect.version
properties, for example:

<properties> 
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> 
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

To avoid a warning message about the HTML 5 template mode being deprecated and the HTML template mode being used instead, you may also want to explicitly configure spring.thymeleaf.mode to be HTML, for example:
spring.thymeleaf.mode: HTML

然后就可以欢快的开撸代码了。



作者:Angeladaddy
链接:https://www.jianshu.com/p/a80d2ff15b47
來源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。



我这边使用的是Gradle,更新了starter中thymeleaf的版本:


compile('org.springframework.boot:spring-boot-starter-thymeleaf'){
     exclude group:'org.thymeleaf'
}
// https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.2.RELEASE'
// https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4
compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '3.0.2.RELEASE'
// https://mvnrepository.com/artifact/nz.net.ultraq.thymeleaf/thymeleaf-layout-dialect
compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '2.1.1'


可以正常访问页面了。还真是这个问题。。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值