SpringBoot - 实现静态资源的访问(附:修改过滤规则、静态资源位置)

一、默认静态资源访问策略

(1)当我们使用 IntelliJ IDEA 创建 Spring Boot 项目,会默认创建 classpath:/static/ 目录,我们直接把静态资源放在这个目录下即可。

 

(2)我们直接在浏览器中输入“http://localhost:8080/1.png”即可看到我们添加的这张图片。

 

二、自定义策略

如果默认的静态资源过滤策略不能满足开发需求,也可以自定义静态资源过滤策略,自定义的方式有如下两种。

1,在配置文件中定义

(1)我们在 application.properties 中直接定义过滤规则和静态资源位置: 

  • 过滤规则改为 /static
  • 静态资源位置仍然是 classpath:/static/ 没有变化
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/

yml版本

spring:
    mvc:
        static-path-pattern:/static/**
    resources:
        static-locations:classpath:/static/

(2)重启项目,我们这次可以在浏览器中输入“http://localhost:8080/static/1.png”来访问添加的静态图片。

 

2,通过 Java 编码定义

(1)这种方式我们只要创建一个类继承 WebMvcConfigurer 接口即可,然后实现该接口的 addResourceHandlers 方法。

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * 静态资源映射
 */
@Component
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

(2)重启项目,效果同上面是一样的。我们同样可以在浏览器中输入“http://localhost:8080/static1.png”来访问添加的静态图片。

posted @ 2021-12-14 13:53  山河永慕~  阅读(656)  评论(0编辑  收藏  举报