10. Spring Boot静态资源处理

10. 静态资源处理

10.1 静态资源映射规则

SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;

里面的静态内部类 WebMvcAutoConfigurationAdapter 中有很多配置方法;

有一个方法:addResourceHandlers 添加资源处理

@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();
    // 第一种:webjars 配置
    if (!registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }

    // 第二种:静态资源配置
  	// staticPathPattern = "/**"
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if (!registry.hasMappingForPattern(staticPathPattern)) {
        customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                             .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
}

所有的 /webjars/* , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源*

10.2 webjars

Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,现在直接导入依赖即可。

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

以jQuery为例:

  1. 首先导入依赖

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.4.1</version>
    </dependency>
    
  2. 查看webjars目录结构,并访问jQuery.js

    img

  3. 输入该路径http://localhost:8080/webjars/jquery/3.4.1/jquery.js即可访问

    img

10.3 第二种静态资源映射规则

staticPathPattern的第二种映射规则 :/** , 访问当前项目的任意资源,它会进入resourceProperties 这个类

// 进入方法
public String[] getStaticLocations() {
    return this.staticLocations;
}

// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS

// 找到路径,这4个路径会被识别,优先级从高到低,后三个都是在resources下创建,默认static
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
    "classpath:/META-INF/resources/",
  	"classpath:/resources/", 
    "classpath:/static/", 
    "classpath:/public/" 
};

ResourceProperties 可以设置和静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即上面数组的内容。

10.4 自定义静态资源路径

# 一旦自定义静态文件夹的路径,自动配置就会生效
spring.resources.static-locations=classpath:/coding/,classpath:/indi/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值