美文网首页
解决SpringBoot不能直接访问templates下的静态资

解决SpringBoot不能直接访问templates下的静态资

作者: YongSiv | 来源:发表于2019-09-26 21:28 被阅读0次

Spriongboot创建的项目,在resources -> templates下的资源是不能直接访问的,没有开放访问权限。这是因为templates文件夹,是放置模板文件的,因此需要视图解析器来解析它。所以必须通过服务器内部进行访问,也就是要走控制器 -> 服务 -> 视图解析器这个流程才行。同时,存在安全问题。比如说,你把你后台的html文件放到templates,而这个文件夹对外又是开放的,就会存在安全隐患。

这里提供两种可以方式访问templates模板下的资源文件
方式一:在application.yml或者application.properties配置文件中将访问权限开放(这种方式不推荐)

spring:
  resources:
    static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, classpath:/templates/

或者

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/

方式二:通过内部controller跳转访问的资源

比如要访问templates下的test.html。先请求内部控制器,由控制器跳转test.html页面

image.png
@Controller
public class Test {

    @GetMapping("/test")
    public String test() {
        return "test";
    }
}

相关文章

网友评论

      本文标题:解决SpringBoot不能直接访问templates下的静态资

      本文链接:https://www.haomeiwen.com/subject/liyoectx.html