SpringBoot的static静态资源访问、参数配置、代码自定义访问规则

1. 静态资源

查看源码如下:

package org.springframework.boot.autoconfigure.web.servlet;
......省略部分......
public class WebMvcAutoConfiguration {
......省略部分......
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                // 将静态资源映射,都添加到映射中心
                this.addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(), "classpath:/META-INF/resources/webjars/");
                this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
                    registration.addResourceLocations(this.resourceProperties.getStaticLocations());
                    if (this.servletContext != null) {
                        ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                        registration.addResourceLocations(new Resource[]{resource});
                    }

                });
            }
        }
......省略部分......
        private void addResourceHandler(ResourceHandlerRegistry registry, String pattern, Consumer<ResourceHandlerRegistration> customizer) {
            if (!registry.hasMappingForPattern(pattern)) {
                ResourceHandlerRegistration registration = registry.addResourceHandler(new String[]{pattern});
                customizer.accept(registration);
                registration.setCachePeriod(this.getSeconds(this.resourceProperties.getCache().getPeriod()));
                registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());
                registration.setUseLastModified(this.resourceProperties.getCache().isUseLastModified());
                this.customizeResourceHandlerRegistration(registration);
            }
        }
......省略部分......
}

1.1 默认静态资源

默认的静态资源目录为:resources/META-INF/resources、resources/public、resources/resources、resources/static。一般用于存放图片、视频、css、js文件

默认的访问静态资源的URL根路径为:/**

所以访问resources/META-INF/resources/baidu1.jpg的URL为http://localhost:8080/baidu1.jpg

1.2 Controller高优先级

如果一个Controller的的@RequestMapping定义的访问路径,和静态资源的URL访问路径一样,则返回Controller的内容

1.3 修改静态资源的URL根路径

可以通过配置参数: spring.mvc.static-path-pattern: /static/**,修改静态资源的URL根路径。此时访问resources/META-INF/resources/baidu1.jpg的URL为http://localhost:8080/static/baidu1.jpg

1.4 修改静态资源的目录

可以通过配置参数:spring.web.resources.static-locations: [classpath:/my-resources/],修改静态资源的目录。会使resources/public、resources/resources、resources/static目录失效,但resources/META-INF/resources目录不失效

1.5 访问webjars依赖包的静态资源

会自动将resources/META-INF/resources/webjars/**,作为静态资源目录

这里我们以jquery为例,进行讲解。在pom.xml添加如下依赖

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.1</version>
        </dependency>

org.webjars.jquery的jar包的目录结构如下:
jquery的jar包的目录结构
然后访问http://localhost:8080/static/webjars/jquery/3.6.1/jquery.js。显示如下:

jquery效果
可以使用spring.mvc.webjars-path-pattern=/wj/**修改webjars路径访问前缀,这样需要通过http://localhost:8080/static/wj/jquery/3.6.1/jquery.js进行访问

1.6 静态资源的关闭

可以通过配置参数:spring.web.resources.add-mappings=false,关闭所有静态资源

1.7 静态资源在浏览器的缓存

  • 浏览器会将静态资源缓存,在缓存时间过期前,不会向服务器进行静态资源的请求。通过配置参数进行设置:spring.web.resources.cache.period=3,单位为秒,默认为0秒

  • cacheControl: HTTP缓存控制。参考: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching。通过spring.web.resources.cache.cachecontrol.max-age=7200设置,默认是7200秒,优先级比spring.web.resources.cache.period高。如果没手动设置该参数,但手动设置了spring.web.resources.cache.period,则period参数生效

  • useLastModified:是否使用最后一次修改。配合cacheControl使用。比如如果浏览器访问了一个静态资源index.js,如果服务器这个资源没有发生变化,下次访问的时候就可以直接让浏览器用自己缓存中的东西,而不用给服务器发请求,此时浏览器状态码为304。通过spring.web.resources.cache.use-last-modified=true设置,默认为true

  • 共享缓存和私有缓存。共享缓存: 客户浏览器和代理服务器都会缓存;私有缓存: 只有客户浏览器会缓存。通过spring.web.resources.cache.cachecontrol.cache-public=truespring.web.resources.cache.cachecontrol.cache-private=false设置。默认由浏览器自行决定,但一般是私有缓存

1.8 静态资源实战

Controller中定义了一个@RequestMapping(“/static/baidu1.jpg”)路径,和resources\META-INF\resources\baidu1.jpg静态资源的路径一样。内容如下:

package com.hh.springboottest.myController;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/static/baidu1.jpg")
    public String helloHandle() {
        return "hello springboot";
    }
}

resources目录内容如下。分别有resources/META-INF/baidu1.jpg、resources/my-resources/baidu2.jpg、resources/public/baidu3.jpg、resources/resources/baidu4.jpg、resources/static/baidu5.jpg

resources目录内容
application.yaml内容如下。分别定义了静态资源访问URL根路径,和静态资源目录

spring:
  mvc:
    static-path-pattern: /static/**

  web:
    resources:
      static-locations: [classpath:/my-resources/]

访问http://localhost:8080/static/baidu1.jpg,效果如下:

访问static/baidu1.jpg
访问http://localhost:8080/static/baidu2.jpg,效果如下:
访问static/baidu2.jpg
http://localhost:8080/static/baidu3.jpg、http://localhost:8080/static/baidu4.jpg、http://localhost:8080/static/baidu5.jpg不能访问

1.9 通过代码自定义静态资源访问规则

如下。添加一个静态资源访问URL,并指定其访问资源路径和缓存时间。其原理是给容器中添加一个WebMvcConfigurer组件,让配置的底层行为都生效

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

// @EnableWebMvc  // 禁用springBoot的默认配置
// 这是一个配置类。给容器中放一个WebMvcConfigurer组件,就能自定义底层。有以下两种方式
//     1. 可以让配置类实现WebMvcConfigurer接口
//     2. 可以在配置类中,将@Bean注解标注在方法上,然后方法返回WebMvcConfigurer
@Configuration
public class WebConfig implements WebMvcConfigurer {


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 默认就会保留以前规则
        // WebMvcConfigurer.super.addResourceHandlers(registry);

        // 自己添加新的规则
        registry.addResourceHandler("/my-static/**")
                .addResourceLocations("classpath:/static1/", "classpath:/static2/")
                .setCacheControl(CacheControl.maxAge(1180, TimeUnit.SECONDS));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值