1、springboot的webmvc对静态资源自动配置代码
public class WebMvcAutoConfiguration { @Override 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)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations( this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } } //配置欢迎页映射 @Bean public WelcomePageHandlerMapping welcomePageHandlerMapping( ApplicationContext applicationContext) { return new WelcomePageHandlerMapping( new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), this.mvcProperties.getStaticPathPattern()); } }
2、规则
1)所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
webjars:以jar包的方式引入静态资源;(http://www.webjars.org/)。
webjars:maven引入webjars的依赖
<!--引入jquery-webjar, 在访问的时候只需要写webjars下面资源的名称即可--> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
导入的webjar的目录结构如下图:
访问webjars: localhost:8080/webjars/jquery/3.3.1/jquery.js
2)"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
localhost:8080/abc === 去静态资源文件夹里面找abc
3)欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;
localhost:8080/ 找index页面
4)所有的 **/favicon.ico 都是在静态资源文件下找;
3、demo
访问 url 为 http://localhost:8089/HelloWorld/, 访问主页 index.html
访问其他静态资源
classpath:public/1.jpg 访问url: localhost:8089/HelloWorld/1.jpg
classpath:resources/2.jpg 访问url: localhost:8089/HelloWorld/2.jpg
classpath:static/3.jpg 访问url: localhost:8089/HelloWorld/3.jpg
classpath:META-INF/resources/4.jpg 访问url: localhost:8089/HelloWorld/4.jpg
webapp/5.jpg 访问url: localhost:8089/HelloWorld/5.jpg
webapp/aWEBINF1/6.jpg 访问url: localhost:8089/HelloWorld/aWEBINF1/6.jpg
# webapp下包含WEB-INF的目录无法访问
webapp/aWEB-INF1/静态资源.txt,无法直接访问
---