SpringBoot2.x入门到项目实战课程系列(第五章)( 二 )

1、所有 /webjars/** 请求 , 都去 classpath:/META-INF/resources/webjars/ 目录找对应资源文件
2、webjars:以jar包的方式引入静态资源;webjars官网:
3、在官网打开资源文件的依赖配置信息 , 然后粘贴到 pom.xml 中
org.webjarsjquery3.3.14、访问 localhost:8080/webjars/jquery/3.3.1/jquery.js 会在下面路径 中查找
SpringBoot2.x入门到项目实战课程系列(第五章)文章插图
5.2.2 其他静态资源映射

  • 在 WebMvcAuotConfiguration.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:/METAINF/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)); }}
  • staticPathPattern 处理其他访问的静态路径 ,从 WebMVCProperties 构造器中获取到 /**
public WebMvcProperties() { this.localeResolver = WebMvcProperties.LocaleResolver.ACCEPT_HEADER; this.dispatchTraceRequest = false; this.dispatchOptionsRequest = true; this.ignoreDefaultModelOnRedirect = true; this.throwExceptionIfNoHandlerFound = false; this.logResolvedException = false; =======接收 /**请求 this.staticPathPattern = "/**"; this.async = new WebMvcProperties.Async(); this.servlet = new WebMvcProperties.Servlet(); this.view = new WebMvcProperties.View(); this.contentnegotiation = new WebMvcProperties.Contentnegotiation(); this.pathmatch = new WebMvcProperties.Pathmatch();}
  • ResourceProperties 根据请求查找资源文件, 从以下 四个路径 中 查找( 静态资源目录 )
@ConfigurationProperties(prefix = "spring.resources",ignoreUnknownFields = false)public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}; private String[] staticLocations; private boolean addMappings; private final ResourceProperties.Chain chain; private final ResourceProperties.Cache cache;"classpath:/META-INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/"