SpringBoot提供了多种方式进行静态资源的访问
1.在classpath路径下resources目录下创建一个文件夹为static,注意名字必须叫static,SpringBoot会去这个路径下进行静态资源的访问
其他的方式就不演示了了
(1)在src/main/resources/目录下创建
static文件夹
(2)在src/main/resources/目录下创建
resources文件夹
(3)在src/main/resources/目录下创建
public文件夹
(4)在src/main/resources/目录下创建
META-INF/resources文件夹
为什么能够直接访问呢,其实在SpringBoot内部已经将其定义好了
通过源码找到相关的信息
下面是WebMvcAutoConfiguration类中的源码信息,该类替代的工作是SpringMVC的相关自动配置
根据名字我们就能知道,该方法是添加资源头信息,也就是资源的访问路径,那么资源的访问路径是哪里来的呢
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
//在这里取出了一个静态资源的映射模式
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//如果有该映射模式就进如if判断
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
静态资源的映射模式
public WebMvcProperties() {
this.localeResolver = WebMvcProperties.LocaleResolver.ACCEPT_HEADER;
this.dispatchTraceRequest = false;
this.dispatchOptionsRequest = true;
this.ignoreDefaultModelOnRedirect = true;
this.throwExceptionIfNoHandlerFound = false;
this.logResolvedException = false;
this.staticPathPattern = "/**";//设置了静态资源的映射模式为全部放行
this.async = new WebMvcProperties.Async();
this.servlet = new WebMvcProperties.Servlet();
this.view = new WebMvcProperties.View();
this.contentnegotiation = new WebMvcProperties.Contentnegotiation();
this.pathmatch = new WebMvcProperties.Pathmatch();
}
获取到了映射模式就进入了下面的代码进行资源头信息的注册
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
最后在类ResourceProperties 找到了默认的资源映射路径
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;