有关咱们web开发的配置SpringBoot都给咱们放到了WebMvcAuotConfiguration这个类中,咱们点开便可看到.它对静态资源的映射路径是怎么样的.html
@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/ 找资源;jquery
webjars:以jar包的方式引入静态资源;web
咱们能够去webjars的官网去看看.http://www.webjars.org/mvc
导入jquery的maven依赖测试一下.app
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
(1)在访问的时候只须要写webjars下面资源的名称便可
localhost:8080/webjars/jquery/3.3.1/jquery.jsmaven
成功的访问到了jquery的静态资源.ide
(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/"
"/":当前项目的根路径this
好比咱们访问localhost:8080/nihao 都会去静态资源文件夹里面找nihaourl
(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必须放在静态资源的文件夹下才能被识别.
运行:
咱们的图标也显示出来了!