网站首页

人工智能P2P分享搜索全网发布信息网站地图标签大全

当前位置:诺佳网 > 电子/半导体 > 嵌入式技术 >

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

时间:2023-06-02 10:04

人气:

作者:admin

标签: 资源  Boot  Spring  静态     

导读:在实际项目开发中,除了程序代码外,还需要一些静态资源,比如公司logo,背景图,css样式文件,js文件等等...

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

图片

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为例):

图片

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

访问结果如下图所示:

图片

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、/ (当前项目的根路径)。

如下图所示:

图片

**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单体应用中关于静态资源映射的说明。

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信