问题描述:
Spring Boot 项目访问resources/templates下静态资源文件报500错误,如果页面显示404错误一定是你地址写错了。
报错内容:
Servlet.service() for servlet [dispatcherServlet] in context with path [/test] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [login], template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [login], template might not exist or might not be accessible by any of the configured Template Resolvers
问题分析:
SpringBoot项目中resources/templates下的静态资源是不能直接访问的,原因是没有开放访问权限的,因为templates下可能存放有后台管理的页面资源,当templates对外开放就会产生安全隐患,所以templates下的资源需要通过ViewResolver(视图解析器)去解析访问
注意
- 这里需要使用@Controller,不能使用@RestController,不然会以Json格式响应到页面,不会进行视图解析。
- 如果application.properties文件配置了二级目录请求地址不需要带上此路径return也不需要返回出去。
- 如果你的静态资源(列如:login.html)放在templates下的一个目录下(列如:pages)则请求地址需要带上也需要return出去。
案例
我这个项目设置了二级目录:server.servlet.context-path=/test
浏览器访问地址:http://localhost:9999/test/pages/login
@Controller
public class PagesController {
// 方法1:
@RequestMapping("{pages}/{login}")
public String pages(@PathVariable String pages,@PathVariable String login){
return pages+"/"+login;
}
//方法二
/*@RequestMapping("pages/login")
public String pages(){
return "pages/login";
}*/
}
SpringBoot模板引擎访问异常解决
本文档介绍了SpringBoot项目访问templates目录下静态资源报500错误的问题,分析了原因在于templates资源未开放直接访问权限。解决方案是通过视图解析器ViewResolver进行访问,并提供了代码示例,演示了如何通过@Controller注解正确返回模板路径。同时提醒注意使用@RestController会导致视图解析失效。案例中展示了在设置二级目录情况下的访问方式。

1万+





