热门关键字:
jquery > jquery教程 > jquery教程 > SpringBoot+thymeleaf+静态资源引入

SpringBoot+thymeleaf+静态资源引入

349
作者:管理员
发布时间:2021/5/20 18:41:38
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=4756
  一、静态资源的映射规则


  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,因为优先级!




如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:jquery
友荐云推荐