静态资源映射规则

我们项目中有许多的静态资源,比如,css,js等文件,这个SpringBoot怎么处理呢?

如果我们是一个web应用,我们的main下会有一个webapp,我们以前都是将所有的页面导在这里面的,对吧!

但是我们现在的pom呢,打包方式是为jar的方式,那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的!

SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置里面,我们可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法

比如:addResourceHandlers

image-20200118105455192

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}

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

webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。使用SpringBoot需要使用webjars,我们可以去搜索一下

网站:https://www.webjars.org/

要使用jQuery,我们只要要引入jQuery对应版本的pom依赖即可!【导入完毕,查看webjars目录结构,并访问Jquery.js文件】

导入依赖:

image-20200118105735183

查看目录结构:

image-20200118105949309

访问:只要是静态资源,SpringBoot就会去对应的路径寻找资源,我们这里访问 :http://localhost:8080/webjars/jquery/3.4.1/jquery.js

image-20200118114354921

那我们项目中要是使用自己的静态资源该怎么导入呢?我们看下一行代码;

我们去找staticPathPattern发现第二种映射规则 : /** , 访问当前的项目任意资源,它会去找 resourceProperties 这个类,我们可以点进去看一下

image-20200118120415433

image-20200118120107218

image-20200118120822089

  • “classpath:/META-INF/resources/“
  • “classpath:/resources/“
  • “classpath:/static/“
  • “classpath:/public/“
  • “/“ :当前项目的根目录

优先级按照顺序。即resources>static>public

静态资源文件夹说完后,我们继续看源码!可以看到一个欢迎页的映射,就是我们的首页!

image-20200118123345463

欢迎页,静态资源文件夹下的所有index.html页面;被 /** 映射。/**又代表着4个静态资源目录。所以只要index.html存放在静态资源文件夹就能被访问。

比如我访问 localhost:8080/ ,就会找静态资源文件夹下的 index.html

image-20200118123731921

我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置

1
spring.resources.static-locations=classpath:/hello/,classpath:/kylin/