6.Spring Boot静态资源映射

Spring Boot 默认为我们提供了 3 种静态资源映射规则:

  • WebJars 映射
  • 默认资源映射
  • 静态首页(欢迎页)映射

1.WebJars 映射

为了让页面更加美观,让用户有更多更好的体验,Web 应用中通常会使用大量的 JS 和 CSS,例如 jQuery,Backbone.js 和 Bootstrap 等等。

WebJars 可以将 Web 前端资源(JS,CSS 等)打成一个个的 Jar 包,然后将这些 Jar 包部署到 Maven 中央仓库中进行统一管理,当 Spring Boot 项目中需要引入 Web 前端资源时,只需要访问 WebJars 官网,找到所需资源的 pom 依赖,将其导入到项目中即可。

所有通过 WebJars 引入的前端资源都存放在当前项目类路径(classpath)下的“/META-INF/resources/webjars/” 目录中。

Spring Boot 通过 MVC 的自动配置类  WebMvcAutoConfiguration 为这些 WebJars 前端资源提供了默认映射规则,部分源码如下。

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        //WebJars 映射规则
        this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (this.servletContext != null) {
                ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                registration.addResourceLocations(new Resource[]{resource});
            }
        });
    }
}

通过以上源码可知,WebJars 的映射路径为“/webjars/**”,即所有访问“/webjars/**”的请求,都会去“classpath:/META-INF/resources/webjars/”查找 WebJars 前端资源。

 

posted @ 2022-07-02 22:23  随遇而安==  阅读(85)  评论(0编辑  收藏  举报