Spring Boot学习系列(四)------静态资源映射
前言
以前在mvc项目中,由于我们的项目最后都是打成war包放在wabapp下面的,所以可以访问到静态资源,现在使用了SpringBoot以后,我们发现没有了webapp文件夹,那么我们的js,css等静态资源又要如何处置呢?
正文
通过查看SpringBoot的源码我们可以发现有一个类:WebMvcAuotConfiguration,他有一下几个方法:
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));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//静态资源文件映射
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
}
}
}
//配置欢迎页
@Bean
public WebMvcAutoConfiguration.WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {
return new WebMvcAutoConfiguration.WelcomePageHandlerMapping(resourceProperties.getWelcomePage());
}
//配置浏览器标签上的小图标
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;
}
}
}
可以看到,在这个类中有以上的方法,分别对静态资源进行了映射:
-
所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
所谓的webjars,就是在网站http://www.webjars.org/中,将我们使用的jQuery等静态资源,打成了maven坐标,这样我们可以直接在pom文件中添加,在这些maven包里,目录是下面这样子的:
在引用的时候可以这样:
<!‐‐引入jquery‐webjar‐‐>在访问的时候只需要写webjars下面资源的名称即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
在访问的时候就要这样访问:localhost:8080/webjars/jquery/3.3.1/jquery.js
-
“/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
"classpath:/META‐INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/":当前项目的根路径
localhost:8080/abc === 去静态资源文件夹里面找abc
-
欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射
localhost:8080/ 找index页面
-
所有的 **/favicon.ico 都是在静态资源文件下找;
我们在更换的时候,只需要将小图标放在静态资源文件夹下面即可,这样就会直接映射到.
总结
SpringBoot的静态资源映射使用起来也是很方便的,直接在application.properties文件里面配置就好了,如果有需要,我们还以单独配置一个文件来使用.