SpringBoot 静态资源处理

SpringBoot 静态资源处理

SpringBoot自动配置的WebMvcAutoConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
        return;
    }
    Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
    CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
    if (!registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
                                             .setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
    }
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if (!registry.hasMappingForPattern(staticPathPattern)) {
        customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                             .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
                                             .setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
    }
}
image-20210111094126659

如果自定义了静态访问路径 则默认资源路径失效

image-20210111103648808

image-20210111103719313

  1. image-20210111102058713

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

    访问 http://127.0.0.1:8080/webjars/jquery/3.5.1/jquery.js 时候

    image-20210111102355540

![image-20210111102447404](https://img-blog.csdnimg.cn/img_convert/5fc8c1958f4e4743e92fdf49b22ba3bd.png)

 通过 staticPathPattern 访问时 

![image-20210111102532280](https://img-blog.csdnimg.cn/img_convert/68f32da666fc6e8be642be3d9b45874c.png)

this.resourceProperties.getStaticLocations()

获取静态资源路径

image-20210111102916292

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

classpath:/META-INF/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/: 当前项目根路径

优先级从高到低

首页 index

image-20210111103317366

从静态资源目录获取index.html

如:/static/index.html

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

classpath:/META-INF/resources/index.html
classpath:/resources/index.html
classpath:/static/index.html 
classpath:/public/index.html
/index.html
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值