spring boot 对 web 静态资源的配置管理是通过配置类 WebMvcAutoConfiguration
来实现的。
顾名思义,WebMvcAutoConfiguration 是web开发的相关配置都放在该类中的。那我们看看静态资源是如何配置的呢?
public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache() .getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } //staticPathPattern的值是 /** String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations( this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } }
从上面的代码中可以解读出两点关键信息:
所有的 "/webjars/**
都去 classpath:/META-INF/resources/webjars/
路径下找静态资源
<dependency> <groupId>org.webjars.bower</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
如果路径是 /**
时,就去以下
classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/
类路径查找资源文件,idea 中的项目路径如下图所示:
3.欢迎页面的映射
private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html"); }
意思是只要在我们的静态资源文件夹中放有 index.html文件,就能自动访问到,比如: http://localhost :8080