首先我们来看一下springBoot对SpringMVC的自动配置做了哪些整合。如果对于springboot自动配置不熟悉可以点击链接看看。
spingboot整合springmvc的自动配置类是WebMvcAutoConfigure.class类,针对静态资源主要进行了以下处理。
webjars引入静态资源
话不多说,直接看源码。在WebMvcAutoConfigure.class类中addResourceHandlers()方法指定 了webjars的路径"classpath:/META-INF/resources/webjars/",所有的/webjars/**,都会从这个路径下去找,例如访问:localhost:8080/webjars/jquery/3.3.1/jquery.js。
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();
//(1)webjars判断
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();
//(2)静态资源路径配置
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
(1)什么是webjars呢。顾名思义就是以jar包的方式导入静态资源。我们可以参考webjars的官网,就可以找到对应的静态资源并在mave配置文件中引入依赖就可以将静态资源导进来了。
(2)从源码上来看处理webjars之外,还对静态资源的位置进行了判断,也就是说,我们自己写的js/css等等静态资源的加载是从以下路径进行加载的,因此当我们访问localhost:8080/**的时候,都是从以下路径去找静态资源的。(注:classpath当前类路径即是src/main/java和src/main/resources下的文件)
①"classpath:/META-INF/resources/",
②"classpath:/resources/",
③"classpath:/static/",
④ “classpath:/public/”
⑤"/":当前项目的根路径
欢迎页面配置
继续来看WebMvcAutoConfigure.class类,其中注册了欢迎界面的bean对象,从中可以发现是从静态资源文件夹下面获取index.html作为欢迎页。
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());//获取欢迎界面
welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
return welcomePageHandlerMapping;
}
private Optional<Resource> getWelcomePage() {
String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}