欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  一、静态资源的映射规则
 
  1.对哪些目录映射?
 
  classpath:/META-INF/resources/
 
  classpath:/resources/
 
  classpath:/static/
 
  classpath:/public/
 
  /:当前项目的根路径
 
  意思是:我们在上面的五个目录下放静态资源文件(比如:jq.js等),可以直接访问(类似以前web项目的webapp下,放到其他目录无法被访问。
 
  2.为什是这几个目录呢?
 
  2.1看源码就知道
 
  SpringBoot自动配置的WebMvcAutoConfirarution.java类:
 
  @Override
 
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
 
  if (!this.resourceProperties.isAddMappings()) {
 
  logger.debug("Default resource handling disabled");
 
  return;
 
  }
 
  Duration cachePeriod=this.resourceProperties.getCache().getPeriod();
 
  CacheControl cacheControl=this.resourceProperties.getCache()
 
  .getCachecontrol().toHttpCacheControl();
 
  if (!registry.hasMappingForPattern("/webjars/**")) {
 
  customizeResourceHandlerRegistration(registry
 
  .addResourceHandler("/webjars/**")
 
  .addResourceLocations("classpath:/META-INF/resources/webjars/")
 
  .setCachePeriod(getSeconds(cachePeriod))
 
  .setCacheControl(cacheControl));
 
  }
 
  String staticPathPattern=this.mvcProperties.getStaticPathPattern();
 
  if (!registry.hasMappingForPattern(staticPathPattern)) {
 
  customizeResourceHandlerRegistration(
 
  registry.addResourceHandler(staticPathPattern)
 
  .addResourceLocations(getResourceLocations(
 
  this.resourceProperties.getStaticLocations()))
 
  .setCachePeriod(getSeconds(cachePeriod))
 
  .setCacheControl(cacheControl));
 
  }
 
  }
 
  ResourceProperties
 
  @ConfigurationProperties(prefix="spring.resources", ignoreUnknownFields=false)
 
  public class ResourceProperties {
 
  //我们可以看到静态资源的映射路径
 
  private static final String[] CLASSPATH_RESOURCE_LOCATIONS={
 
  "classpath:/META-INF/resources/", "classpath:/resources/",
 
  "classpath:/static/", "classpath:/public/" };
 
  ...
 
  }
 
  总的来说:
 
  WebMvcAutoConfiguration类自动为我们注册了如下目录为静态资源目录,也就是说直接可访问到资源的目录。
 
  classpath:/META-INF/resources/
 
  classpath:/resources/
 
  classpath:/static/
 
  classpath:/public/
 
  /:当前项目的根路径
 
  优先级从上到下。
 
  所以,如果static里面有个index.html,public下面也有个index.html,则优先会加载static下面的index.html,因为优先级!

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h62036.shtml