当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot中的静态资源访问的实现

SpringBoot中的静态资源访问的实现

2020年09月15日  | 移动技术网IT编程  | 我要评论
一、说在前面的话我们之间介绍过springboot自动配置的原理,基本上是如下:xxxxautoconfiguration:帮我们给容器中自动配置组件;xxxxproperties:配置类来封装配置文

一、说在前面的话

我们之间介绍过springboot自动配置的原理,基本上是如下:

xxxxautoconfiguration:帮我们给容器中自动配置组件;
xxxxproperties:配置类来封装配置文件的内容;

二、静态资源映射规则

1、对哪些目录映射?

classpath:/meta-inf/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/:当前项目的根路径

2、什么意思?

就我们在上面五个目录下放静态资源(比如:a.js等),可以直接访问(http://localhost:8080/a.js),类似于以前web项目的webapp下;放到其他目录下无法被访问。

3、为什么是那几个目录?

3.1、看源码

我们一起来读下源码,这个是springboot自动配置的webmvcautoconfiguration.java类来帮我们干的。

@override
public void addresourcehandlers(resourcehandlerregistry registry) {
  if (!this.resourceproperties.isaddmappings()) {
    logger.debug("default resource handling disabled");
    return;
  }
  integer cacheperiod = this.resourceproperties.getcacheperiod();
  if (!registry.hasmappingforpattern("/webjars/**")) {
    customizeresourcehandlerregistration(
        registry.addresourcehandler("/webjars/**")
            .addresourcelocations(
                "classpath:/meta-inf/resources/webjars/")
        .setcacheperiod(cacheperiod));
  }
  string staticpathpattern = this.mvcproperties.getstaticpathpattern();
  if (!registry.hasmappingforpattern(staticpathpattern)) {
    customizeresourcehandlerregistration(
        registry.addresourcehandler(staticpathpattern)
            .addresourcelocations(
                this.resourceproperties.getstaticlocations())
        .setcacheperiod(cacheperiod));
  }
}

3.2、分析源码

我们重点分析后半截,前半截后面会介绍。

// staticpathpattern是/**
string staticpathpattern = this.mvcproperties.getstaticpathpattern();
if (!registry.hasmappingforpattern(staticpathpattern)) {
  customizeresourcehandlerregistration(
      registry.addresourcehandler(staticpathpattern)
          .addresourcelocations(
              this.resourceproperties.getstaticlocations())
      .setcacheperiod(cacheperiod));
}
this.resourceproperties.getstaticlocations()
========>
resourceproperties
public string[] getstaticlocations() {
  return this.staticlocations;
}
========>
private string[] staticlocations = resource_locations;
========>
private static final string[] resource_locations;
private static final string[] servlet_resource_locations = { "/" };
private static final string[] classpath_resource_locations = {
      "classpath:/meta-inf/resources/", "classpath:/resources/",
      "classpath:/static/", "classpath:/public/" };
========>
static {
  // 可以看到如下是对上面两个数组进行复制操作到一个新数组上,也就是合并。
  resource_locations = new string[classpath_resource_locations.length
      + servlet_resource_locations.length];
  system.arraycopy(servlet_resource_locations, 0, resource_locations, 0,
      servlet_resource_locations.length);
  system.arraycopy(classpath_resource_locations, 0, resource_locations,
      servlet_resource_locations.length, classpath_resource_locations.length);
}
所以上述代码经过我的翻译后成为了如下样子:

registry.addresourcehandler("/**").addresourcelocations(
  "classpath:/meta-inf/resources/", "classpath:/resources/",
      "classpath:/static/", "classpath:/public/", "/")
  // 设置缓存时间
  .setcacheperiod(cacheperiod));

3.3、一句话概括

webmvcautoconfiguration类自动为我们注册了如下目录为静态资源目录,也就是说直接可访问到资源的目录。

classpath:/meta-inf/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/:当前项目的根路径

优先级从上到下。

所以,如果static里面有个,public下面也有个,则优先会加载static下面的,因为优先级!

4、默认首页

ps:就是直接输入ip:port/项目名称默认进入的页面。

4.1、看源码

webmvcautoconfiguration.java

@bean
public welcomepagehandlermapping welcomepagehandlermapping(
   resourceproperties resourceproperties) {
  return new welcomepagehandlermapping(resourceproperties.getwelcomepage(),
     this.mvcproperties.getstaticpathpattern());
}

4.2、分析源码

resourceproperties.getwelcomepage()
========>
public resource getwelcomepage() {
  // 遍历默认静态资源目录后面拼接个的数组
  // 比如:[/static/, /public/等等]
  for (string location : getstaticwelcomepagelocations()) {
    resource resource = this.resourceloader.getresource(location);
    try {
      if (resource.exists()) {
        resource.geturl();
        return resource;
      }
    }
    catch (exception ex) {
      // ignore
    }
  }
  return null;
}
========>
// 下面这段代码通俗易懂,就是给默认静态资源目录后面拼接个并返回,比如:/static/
private string[] getstaticwelcomepagelocations() {
  string[] result = new string[this.staticlocations.length];
  for (int i = 0; i < result.length; i++) {
    string location = this.staticlocations[i];
    if (!location.endswith("/")) {
      location = location + "/";
    }
    result[i] = location + "";
  }
  return result;
}

所以上述代码经过我的翻译后成为了如下样子:

return new welcomepagehandlermapping(
  "classpath:/meta-inf/resources/",
  "classpath:/resources/",
  "classpath:/static/",
  "classpath:/public/",
  "/"
  , "/**");

4.3、一句话概括

webmvcautoconfiguration类自动为我们注册了如下文件为默认首页。

classpath:/meta-inf/resources/
classpath:/resources/
classpath:/static/ 
classpath:/public/
/

优先级从上到下。

所以,如果static里面有个,public下面也有个,则优先会加载static下面的,因为优先级!

5、favicon.ico

ps:就是这个图标。

5.1、看源码

@configuration
@conditionalonproperty(value = "spring.mvc.favicon.enabled", matchifmissing = true)
public static class faviconconfiguration {

  private final resourceproperties resourceproperties;

  public faviconconfiguration(resourceproperties resourceproperties) {
   this.resourceproperties = resourceproperties;
  }

  @bean
  public simpleurlhandlermapping faviconhandlermapping() {
   simpleurlhandlermapping mapping = new simpleurlhandlermapping();
   mapping.setorder(ordered.highest_precedence + 1);
   mapping.seturlmap(collections.singletonmap("**/favicon.ico",
      faviconrequesthandler()));
   return mapping;
  }

  @bean
  public resourcehttprequesthandler faviconrequesthandler() {
   resourcehttprequesthandler requesthandler = new resourcehttprequesthandler();
   requesthandler
      .setlocations(this.resourceproperties.getfaviconlocations());
   return requesthandler;
  }

}

5.2、分析源码

// 首先可以看到的是可以设置是否生效,通过参数spring.mvc.favicon.enabled来配置,若无此参数,则默认是生效的。
@conditionalonproperty(value = "spring.mvc.favicon.enabled", matchifmissing = true)
========》
// 可以看到所有的**/favicon.ico都是在faviconrequesthandler()这个方法里找。
mapping.seturlmap(collections.singletonmap("**/favicon.ico", faviconrequesthandler()));
========》
faviconrequesthandler().this.resourceproperties.getfaviconlocations()
// 就是之前的五个静态资源文件夹。  
list<resource> getfaviconlocations() {
  list<resource> locations = new arraylist<resource>(
      this.staticlocations.length + 1);
  if (this.resourceloader != null) {
    for (string location : this.staticlocations) {
      locations.add(this.resourceloader.getresource(location));
    }
  }
  locations.add(new classpathresource("/"));
  return collections.unmodifiablelist(locations);
}

5.3、一句话概括

只要把favicon.ico放到如下目录下,就会自动生效。

classpath:/meta-inf/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/:当前项目的根路径

6、webjars

6.1、看源码

webmvcautoconfiguration

@override
public void addresourcehandlers(resourcehandlerregistry registry) {
  if (!this.resourceproperties.isaddmappings()) {
    logger.debug("default resource handling disabled");
    return;
  }
  integer cacheperiod = this.resourceproperties.getcacheperiod();
  if (!registry.hasmappingforpattern("/webjars/**")) {
    customizeresourcehandlerregistration(
        registry.addresourcehandler("/webjars/**")
            .addresourcelocations(
                "classpath:/meta-inf/resources/webjars/")
        .setcacheperiod(cacheperiod));
  }
  string staticpathpattern = this.mvcproperties.getstaticpathpattern();
  if (!registry.hasmappingforpattern(staticpathpattern)) {
    customizeresourcehandlerregistration(
        registry.addresourcehandler(staticpathpattern)
            .addresourcelocations(
                this.resourceproperties.getstaticlocations())
        .setcacheperiod(cacheperiod));
  }
}

6.2、分析源码

这次我们来分析前半截。

integer cacheperiod = this.resourceproperties.getcacheperiod();
if (!registry.hasmappingforpattern("/webjars/**")) {
  customizeresourcehandlerregistration(
      registry.addresourcehandler("/webjars/**")
          .addresourcelocations(
              "classpath:/meta-inf/resources/webjars/")
      .setcacheperiod(cacheperiod));
}

6.3、一句话概括

所有/webjars/**都从classpath:/meta-inf/resources/webjars/路径下去找对应的静态资源。

6.4、什么是webjars?

就是以jar包的方式引入静态资源。

官网地址:。类似于maven仓库。

我们可以做个例子,将jquery引入到项目中

<dependency>
  <groupid>org.webjars</groupid>
  <artifactid>jquery</artifactid>
  <version>3.3.1</version>
</dependency>

看项目依赖

会自动为我们引入jquery,要怎么使用呢?我们上面说过:

所有/webjars/*都从classpath:/meta-inf/resources/webjars/路径下去找对应的静态资源。

所以我们启动项目,访问:即可。

必须在这几个路径下springboot才会扫描到!

"classpath:/meta-inf/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径

到此这篇关于springboot中的静态资源访问的实现的文章就介绍到这了,更多相关springboot 静态资源访问内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网