静态资源映射规则:
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;
我们可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;
有一个方法:addResourceHandlers 添加资源处理

  1. @Override
  2. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  3. if (!this.resourceProperties.isAddMappings()) {
  4. // 已禁用默认资源处理
  5. logger.debug("Default resource handling disabled");
  6. return;
  7. }
  8. // 缓存控制
  9. Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
  10. CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
  11. // webjars 配置
  12. if (!registry.hasMappingForPattern("/webjars/**")) {
  13. customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
  14. .addResourceLocations("classpath:/META-INF/resources/webjars/")
  15. .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
  16. }
  17. // 静态资源配置
  18. String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  19. if (!registry.hasMappingForPattern(staticPathPattern)) {
  20. customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
  21. .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
  22. .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
  23. }
  24. }

读一下源代码:比如所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;

Webjars

Webjars本质就是以jar包的方式引入我们的静态资源
官网:https://www.webjars.org
比如导入jQuery依赖后,访问http://localhost:8080/webjars/jquery/3.4.1/jquery.js即可
访问:只要是静态资源,SpringBoot就会去对应的路径寻找资源

映射规则二

以下四个目录存放的静态资源可以被我们识别:

  1. "classpath:/META-INF/resources/"
  2. "classpath:/resources/"
  3. "classpath:/static/"
  4. "classpath:/public/"

比如我们访问 http://localhost:8080/1.js , 他就会去这些文件夹中寻找对应的静态资源文件;

总结

image.png
image.png

静态资源文件夹下的所有 index.html 页面;被 /** 映射。