有關我們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必須放在靜態資源的文件夾下才能被識別.
運行:
我們的圖標也顯示出來了!