解决:template might not exist or might not be accessible by any of the configured Template Resolvers报错

问题描述:

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(视图解析器)去解析访问

注意

  1. 这里需要使用@Controller,不能使用@RestController,不然会以Json格式响应到页面,不会进行视图解析。
  2. 如果application.properties文件配置了二级目录请求地址不需要带上此路径return也不需要返回出去。
  3. 如果你的静态资源(列如: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";
    }*/
}

在这里插入图片描述
了解Spring MVC 执行流程请点击


版权声明:本文为weixin_53106424原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。