我們知道, 在之前的springmvc項目中,如果我們需要使用那個jar包,就把該jar包放在項目的webapp下,就可以在項目中使用,但是在SpringBoot中,我們怎麼辦呢? 使用 webjars的方式: 以jar包方式引入靜態資源。
網址如下: WebJars
其提供了常用的前端框架如 npm、jquery、Bootstrap、Swagger UI等,並且maven依賴的方式交給我們,我們只要選好版本,在pom文件中加入該依賴 的webjar就可以使用了。
例如: 想要引用 jquery,那就複製jquery的相關依賴,並且添加到 pom文件中:
引入之後,我們還要了解 springboot對webjars的映射規則是怎麼樣的。
在SpringBoot中,SpringMvc的相關配置都在 WebMvcAutoConfiguration中,在該配置中,我們主要看以下方法:
addResourceHandlers方法 ,其代碼如下:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
請看:
1) 所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找資源;這就是springboot的映射規則 。
引入jquery的依賴之後,我們可以看到jquery的目錄結構如下:
完全符合SpringBoot的映射規則 。
此時我們就可以進行簡單的測試: localhost:8080/webjars/jquery/3.3.1/jquery.js,發現能訪問到該js文件。
如果是自己的靜態資源文件 ,就會匹配以下規則:
2) /** 訪問當前項目的任何資源(靜態資源的文件夾)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/" //當前項目的根路徑
如下圖所示:
我們如果想訪問 static目錄下的assert下的js文件,那麼就可以直接通過路徑 /asserts/js/Chart.min.js訪問到:
3) 歡迎頁的映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext),
applicationContext,
this.getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
靜態資源文件夾下的所有index.html頁面,被 /** 映射 ;
eg 瀏覽器訪問 localhost:8080/ ,由於也符合/** ,所以就會去找 index頁面。
在資源文件夾下添加一個 index.html文件 ,然後訪問測試如下:
4) 配置 喜歡的圖標
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
任何路徑下的 **/favicon.ico 同樣也都映射到 靜態資源文件夾下找。
eg. 我們在public目錄下添加一個 favicon.ico ,然後刷新剛纔的頁面:發現圖標發生了變化:
原本是: 變成了:
當然了,我們也可以修改靜態資源文件夾的位置: 在application.properties文件中,
通過 spring.resources.static-location=classpath:////// 來指定新的位置。
請注意:指定新的靜態資源文件夾的位置之後,springboot默認的就不生效了,也就是說我們要通過我們指定的文件夾的位置去訪問靜態資源,以前的不能訪問。
看,已經找不到頁面了。