Spring Boot对静态资源的映射规则

电子说

1.3w人已加入

描述

在实际项目开发中,除了程序代码外,还需要一些静态资源,比如公司logo,背景图,css样式文件,js文件等等,这里介绍一下单体应用中Spring Boot对静态资源的一些映射规则。(此处的单体应用指非前后端分离、非微服务、非SOA架构的简易版项目,具体区别看下图所示)

CSS

Spring Boot对静态资源的映射规则

在Spring Boot中,SpringMVC的相关配置都默认在WebMvcAutoConfiguration类中,具体源码请在IDE中自行搜索查看。

1、 所有/webjars/**(/**表示访问此路径下的任何资源,都会去classpath:/META-INF/resources/webjars/下寻找资源(webjars就是以jar包方式引入资源到项目中), 相关源码如下:

// WebMvcAutoConfiguration.java
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   if (!this.resourceProperties.isAddMappings()) {
      logger.debug("Default resource handling disabled");
      return;
   }
   addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
   addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) - > {
      registration.addResourceLocations(this.resourceProperties.getStaticLocations());
      if (this.servletContext != null) {
         ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
         registration.addResourceLocations(resource);
      }
   });
}
private void addResourceHandler(ResourceHandlerRegistry registry, String pattern, String... locations) {
   addResourceHandler(registry, pattern, (registration) - > registration.addResourceLocations(locations));
}
private void addResourceHandler(ResourceHandlerRegistry registry, String pattern,
      Consumer< ResourceHandlerRegistration > customizer) {
   if (registry.hasMappingForPattern(pattern)) {
      return;
   }
   ResourceHandlerRegistration registration = registry.addResourceHandler(pattern);
   customizer.accept(registration);
   registration.setCachePeriod(getSeconds(this.resourceProperties.getCache().getPeriod()));
   registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());
   registration.setUseLastModified(this.resourceProperties.getCache().isUseLastModified());
   customizeResourceHandlerRegistration(registration);
}

结构如图所示(以jquery为例):

CSS

jquery的maven依赖如下:

< dependency >
    < groupId >org.webjars.npm< /groupId >
    < artifactId >jquery< /artifactId >
    < version >3.6.0< /version >
< /dependency >

访问示例地址如下:

localhost:8080/webjars/jquery/3.6.0/dist/jquery.js

访问结果如下图所示:

CSS

2、 /**,访问当前项目下的任何静态资源,相关源码如下:

// WebMvcAutoConfiguration.java
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) - > {
   registration.addResourceLocations(this.resourceProperties.getStaticLocations());
   if (this.servletContext != null) {
      ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
      registration.addResourceLocations(resource);
   }
});


// WebMvcProperties.java
public String getStaticPathPattern() {
   return this.staticPathPattern;
}
private String staticPathPattern = "/**";


// WebProperties.java
public String[] getStaticLocations() {
   return this.staticLocations;
}
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
      "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
/**
 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
 * /resources/, /static/, /public/].
 */
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

由源码可知,静态资源的访问路径有如下几个:

1、classpath:/META-INF/resources/ ;

2、classpath:/resources/;

3、classpath:/static/;

4、classpath:/public/;

5、/ (当前项目的根路径)。

如下图所示:

CSS

**3、 **欢迎页: 静态资源文件夹下的index.html页面,相关源码如下:

// WebMvcAutoConfiguration.java
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
      FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
   WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
         new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
         this.mvcProperties.getStaticPathPattern());
   welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
   welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
   return welcomePageHandlerMapping;
}


private Resource getWelcomePage() {
   for (String location : this.resourceProperties.getStaticLocations()) {
      Resource indexHtml = getIndexHtml(location);
      if (indexHtml != null) {
         return indexHtml;
      }
   }
   ServletContext servletContext = getServletContext();
   if (servletContext != null) {
      return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
   }
   return null;
}
private Resource getIndexHtml(String location) {
   return getIndexHtml(this.resourceLoader.getResource(location));
}
private Resource getIndexHtml(Resource location) {
   try {
      Resource resource = location.createRelative("index.html");
      if (resource.exists() && (resource.getURL() != null)) {
         return resource;
      }
   }
   catch (Exception ex) {
   }
   return null;
}


// WebMvcProperties.java
public String getStaticPathPattern() {
   return this.staticPathPattern;
}
private String staticPathPattern = "/**";

根据源码可知,欢迎页是被/**映射,也解释了首页名称为index.html的原因。

4、 自定义静态资源文件夹,在配置文件application.properties中添加如下配置,就会覆盖掉项目的默认配置,示例代码如下:

spring.web.resources.static-locations=classpath:/brevity/,classpath:/github/

以上就是Spring Boot单体应用中关于静态资源映射的说明。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分