springboot无法访问templates下的html页面和Error resolving template "xxx"的解决方案
·
错误如下
Error resolving template “xxx”, template might not exist or might not be accessible by any of the configured Template Resolvers
分析与解决
springboot整合了springmvc的拦截功能。拦截了所有的请求。默认放行的资源是:resources/static/ 目录下所有静态资源。(不走controller控制器就能直接访问到资源)
- html页面如果放在resources/templates目录下,则需要走controller控制器,controller放行,允许该资源访问,该资源才能被访问到。否则就会报404错误(它不可以直接被访问。如果你想将templates变得像static一样,就可以在application.properties中添加如下配置。直接放行该目录下的所有资源.不建议这样做。可能会造成thymeleaf模板标签的代码无法解析。并且已经有了类似的目录static了)
spring.resources.static-locations=classpath:/templates/
- 检查配置是否正确
- 是否添加了thymeleaf依赖,idea是否安装了thymeleaf插件,没有请安装该插件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 可尝试添加如下配置:增加解决问题的成功率 -->
<!-- <dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<!– 配置将哪些资源文件(静态文件/模板文件/mapper文件)加载到tomcat输出目录里 –>
<build>
<resources>
<resource>
<directory>src/main/java</directory><!–java文件的路径–>
<includes>
<include>**/*.*</include>
</includes>
<!– <filtering>false</filtering>–>
</resource>
<resource>
<directory>src/main/resources</directory><!–资源文件的路径–>
<includes>
<include>**/*.*</include>
</includes>
<!– <filtering>false</filtering>–>
</resource>
</resources>
</build>-->
- thymeleaf 2.X 版本要求templates下的html必须要严格按照thymeleaf 2.X 版本的要求来编写html,可升级为thymeleaf 3.X 版本。添加配置如下(在springboot中指定thymeleaf的版本):
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
- 在application.properties文件中配置视图解析规则,以及thymeleaf对html的thymeleaf规范的严格程度。使得resolving template能够被正确解析
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.mode: HTML
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
#声明thymeleaf使用非严格的html。
#spring.thymeleaf.check-template=true
#spring.thymeleaf.check-template-location=true
#spring.thymeleaf.mode=LEGACYHTML5
测试controller如下:
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/ok")
public String ok(){
return "ok";
}
}


魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)