寫在前面:
環境:Spring Boot版本:1.5.10.RELEASE
文章中相關源碼的分析,都是以WebMvcAutoConfiguration
類爲起點,在其基礎上再進行相關的分析。
一、訪問/webjars/**路徑
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
}
}
}
從源碼可知,所有/webjars/**
的請求都會到"classpath:/META-INF/resources/webjars/"
路徑下尋找相關的資源。
這裏解釋一下,所謂的webjars即是以jar包的方式引入靜態資源。
開發時,我們所需的一些前端資源可以到webjars官網以maven的方式進行引入。
這裏以引入jquery爲例進行演示:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
引入jquery依賴後,我們在External Libraries下找到如下的結構圖。
我們在瀏覽器地址欄輸入localhost:8080/webjars/jquery/3.3.1/jquery.js
將會看到jquery.js的代碼。
溫馨提示:如果在application.properties中配置server.context-path=/crud
路徑後,我們在訪問的時候需要添加/crud,如:http://localhost:8080/crud
/webjars/jquery/3.3.1/jquery.js
二、訪問/**路徑
經上述分析,/**
訪問當前項目的任何資源,都去(靜態資源的文件夾
)找映射,如下:
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑
現有靜態資源放在static目錄下,我們可以訪問http://localhost:8080/asserts/js/Chart.min.js
三、訪問/**路徑下的歡迎頁
首頁(index.html)可以存放的位置爲靜態資源存放的位置。如下
四、訪問**/favicon.ico路徑
public static class FaviconConfiguration {
private final ResourceProperties resourceProperties;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
經上分析,favicon.ico存放的位置依然爲靜態資源文件的路徑下。