在之前做项目时遇到了一个报错Error resolving template [index.html], template might not exist or might not be accessible by any of the configured Template Resolvers
这种报错在在项目使用了thymeleaf后才会发生的,去网上搜索的话通常都是说有2种情况才会发生但是其实引发报错的因素并不只有这2种请况,我也去试了以下两种情况,但我的报错原因都不符合这两种,后来通过排查我找到了报错的原因是target/templates目录下没有html文件.
先说一下我尝试网上提出的两种解决办法及使用后的情况
第一种,去将@Controller 注解 换成 @RestConteroller,或者是不更换在方法前面加一个@ResponseBody注解,如下图 ;
这个我去试了一下用这种方法去运行项目的话不会报错,但是问题并没有解决,因为访问网页得到的并不是我编写的index.html网页,而是如图下这种情况
第二种,在方法return "index.html";加上'/',写成 return "/index.html"如下图
上面图里的话是可以加 " / ",如果想要这里不加 " / "的话那就要在application.yml文件的thymeleaf模板配置文件中的prefix: classpath:/templates 后面加上" / "写成 prefix: classpath:/templates/ 如下图,反正这两个地方一定要有一个" / ", 否则就会报错.
我的当时报错的情况与上面的不同,但报出错误却也是 Error resolving template [index.html], template might not exist or might not be accessible by any of the configured Template Resolvers,先给大家看一下我的代码如下
<!--pom.xml配置代码-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@Controller //Controller层
public class HtmlController {
@RequestMapping("index")
public String index(){
System.out.println("进入主页面");
return "index.html";
}
}
spring:
#设置thymeleaf模板渲染
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
servlet:
content-type: text/html
cache: false
在正常情况下这样是不会报出错误的,但是我却报出了这个错误,后来发现运行后target/templates目录下没有找到我的 index.html 文件,所以才报出错误,这是因为运行时文件没有自动拷贝到target/templates目录下,需要去pom.xml里面去配置把resources目录下的文件在运行时自动拷贝过去pom.xml 配置如下
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
其实如果pom.xml文件里面有了<parent>配置 如下图 :一般来说都会把文件自动拷贝到target目录但是有些情况下创建项目后是没有<parent>相关配置的,我之用的 IDEA 2019.3.3版 创建项目后pom.xml文件就没有<parent>相关配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/>
</parent>
pom.xml文件配置好后先把target目录的文件都删除掉(放心里面的都是编译文件,运行后又会回来)删完后点击一下运行,再去target/templates目录下找一下有没有html文件,有的话那代表拷贝过去了,没有的话就是pom.xml里面没有配置好.
如果也不是这种情况的话可以查一下IDEA的相关配置,或者是JDK的一些文件问题,例如IDEA编码设置,JDK中否有些文件缺失了,我这两种原因都出现过,而且在大多数情况下是不会出现问题的,这会让我们误以为它们没有问题,其实只是触发几率小或者是只是只会出现某一功能上.
更多推荐
解析模板 [index.html] 时出错,模板可能不存在或可能无法被任何已配置的模板解析器访问
发布评论