org.thymeleaf.exceptions.TemplateInputException:template might not exist or might not be accessible by any of the configured Template Resolvers

小小牛博客

1.Thymeleaf

最近大量使用SpringBoot替代Spring,然而SpringBoot推荐用thymeleaf取代JSP,既然官方都推荐了那就用呗
妹的,刚开始用到处都是坑,得踩一段时间才能踩完。

2.格式检测

Thymeleaf的格式检测有点严格,连html标签没闭合也报错,使用VUE等前端框架时会用很多自定义的标签,会无限报错的,很是不习惯。可以通过引入额外的库解决

引入依赖:

1
2
3
4
5
<dependency>  
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>

配置application.yml:

1
2
3
thymeleaf:
cache: false
mode: LEGACYHTML5

OK! 不会报错了

3.Thymeleaf模板布局–报错TemplateInputException

来说说Thymeleaf的网页布局,jsp布局我们用include引入代码片段组装网页,Thymeleaf也有类似的功能

但是,TMD报错了:

1
2
3
4
5
6
7
8
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "html/index", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335) ~[thymeleaf-spring4-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring4-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1286) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]

这很明显是路径问题,报错原因是Thymeleaf默认模板存放在resources/templates下面,而我在里面多放了一个html文件夹然后

1
return "html/index";

这样本来没错是可以访问页面的,但是在首页引入其他模板的时候

1
<div th:replace="header/header :: header"></div>

这样Thymeleaf会去默认的resources/templates寻找header/header.html模板所以报错了。

解决办法:修改默认路径为resources/templates/html

1
2
thymeleaf:
prefix: classpath:/templates/html/

以前的Controller也要改一下

1
return "index";

这样就可以愉快的写代码了^-^