1、思考:SpringBoot是没有webapp目录的那么我们的资源( *.css , *.js …)应该放在哪里?
2、通过源码探析
1、研究SpringBoot关于MVC的自动配置
1、所有关于MVC的相关配置都在WebMvcAutoConfiguration(视图解析,静态资源过滤)
2、addResourceHandlers静态资源处理方法
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//1、禁止默认规则的一个配置,如果手动添加了资源映射路径配置,则自动配置就会失效
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
//缓存控制
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
//判断是否存在一个映射路径/webjars/**
//addResourceHandler处理逻辑/webjars/a.js
//addResourceLocations 处理资源的地址classpath:/META-INF/resources/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();
//如果访问映射的路径是staticPathPattern = "/**";
if (!registry.hasMappingForPattern(staticPathPattern)) {
//this.resourceProperties.getStaticLocations()获取四个常量路径
// private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
//"classpath:/META-INF/resources/",
//"classpath:/resources/",
//"classpath:/static/",
//"classpath:/public/" };
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
2、基于源码分析引出加载资源方式
1、第一种:webjars
1、什么是webjars:使用maven,通过jar包的方式,引入前端静态资源
2、导入maven
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
2、测试访问
2、第二种:
1、4种路径,建项目是默认只有static
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/",// 在 starter 中使用! SWAGGER-UI
"classpath:/resources/", // 文件资源
"classpath:/static/", // 静态资源
"classpath:/public/" // 公共的,图标......
}
2、四种路径加载加载先后顺序:
META-INF/resources>resources>public>static
3、第二种:自己配置了资源路经的映射,默认的配置就会失效
注:看源码配置了自己的映射路径默认的应该都失效,但是META-INF下的为啥没失效呢??待解答