有关我们web开发的配置SpringBoot都给我们放到了WebMvcAuotConfiguration这个类中,我们点开即可看到.它对静态资源的映射路径是怎么样的.
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration( registry.addResourceHandler("/webjars/**") .addResourceLocations( "classpath:/META-INF/resources/webjars/") .setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); //静态资源文件夹映射 if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations( this.resourceProperties.getStaticLocations()) .setCachePeriod(cachePeriod)); } }
我们可以看到所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
(1)在访问的时候只需要写webjars下面资源的名称即可
localhost:8080/webjars/jquery/3.3.1/jquery.js
成功的访问到了jquery的静态资源.
(2)"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射.
分析源码
if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations( this.resourceProperties.getStaticLocations()) .setCachePeriod(cachePeriod)); } }
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
比如我们访问localhost:8080/nihao 都会去静态资源文件夹里面找nihao
(3)欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射
@Bean public WelcomePageHandlerMapping welcomePageHandlerMapping( ResourceProperties resourceProperties) { return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); }
也就是在localhost:8080/ 找index页面.放在静态资源文件夹就可以找到他为我们自动配置了匹配的前缀(index)和后缀(html).
(4)所有的 **/favicon.ico 都是在静态资源文件下找
配置我们喜欢的图标
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler .setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; } }
我们图标的名字必须是faricon.ico必须放在静态资源的文件夹下才能被识别.
运行:
我们的图标也显示出来了!