关于SpringBoot如何访问静态资源

在SpringBoot中我们一般通过以下方式来处理静态资源

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

优先级从高到低

默认使用是static

因为优先级的关系

一般public放用户界面

static我们放图片等

至于另外两个就放一些核心的部分


jar包一般使用的是webjars的方式

比如jquery的jar包
在这里插入图片描述
我们想访问这个jquery.js只需要这样访问
localhost:8080/webjars/jquery/3.3.1/jquery.js


我们很容易发现 META-INF/resources是不需要写的

同理 访问我们自己的静态资源也不需要
在这里插入图片描述
比如想要访问1.js 直接从以上四个路径中挑一个放入1.js

然后localhost:8080/1.js 即可

源码

在WebMvcAutoConfiguration下
有这么个方法

 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).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
                }

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

            }
        }

这个方法判断了三种情况

  1. 自定义路径
  2. 使用webjars
  3. 我们放置在上述的几种地方

我们点开

getStaticLocations()

得到

 public String[] getStaticLocations() {
            return this.staticLocations;
        }

再点staticLocations
发现这两个属性

 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
 private String[] staticLocations;

我们再看构造方法

public Resources() {
            this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
            //一些其他的东西 我没有CV
        }

就可以得到我们上述的路径了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值