springboot直接访问templates下静态页面

springboot直接访问templates下静态页面

sringboot资源文件夹resources下默认有两个子文件夹:static、templates

关于这个文件夹的访问权限可以通过源码了解:

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

由源码可知

static文件夹下的资源是可以直接访问的,一般用来存放静态资源(源码中目录下的资源都可以直接访问)

但是templates下的资源是受保护的,不允许直接访问。如果要访问,可以在maven引入thymeleaf依赖,然后通过controller访问

如果要跟static一样可以直接被访问,则需要在application.yml中进行配置

百度的配置:

spring:
  resources:
    static-locations: classpath:/static/,classpath:/templates/

但是配置之后显示该配置已经过时,不建议使用

再次查看源码:

@DeprecatedConfigurationProperty(
    replacement = "spring.web.resources.static-locations"
)
public String[] getStaticLocations() {
    return super.getStaticLocations();
}

由源码可知配置方式为:

spring:
  web:
    resources:
      static-locations: classpath:/static/,classpath:/templates/

至此,templates下的页面就可以直接被访问了

记得快乐
原文地址:https://www.cnblogs.com/Y-wee/p/14711878.html