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