zoukankan      html  css  js  c++  java
  • 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”来访问添加的静态图片。

    早年同窗始相知,三载瞬逝情却萌。年少不知愁滋味,犹读红豆生南国。别离方知相思苦,心田红豆根以生。
  • 相关阅读:
    腾讯精品课程
    什么都没有,先空出来!
    Python3-super().__init()__
    Python3-模块
    Python3-单例模式
    Python3-私有化修改
    Python3-私有属性
    Python3-面向对象-魔术方法
    Python3-面向对象-四种方法
    Python3-迭代器
  • 原文地址:https://www.cnblogs.com/shanheyongmu/p/15687608.html
Copyright © 2011-2022 走看看