Springboot静态资源映射

Springboot静态资源映射

 

Springboot默认支持的静态资源路径 ,即 /**,默认下面三个路径
/src/main/resources/public
/src/main/resources/resources
/src/main/resources/static

image.png


我们在 三个默认路径下添加 image2.jpg image3.jpg image4.jpg三个图片,分别访问
http://localhost:8080/image2.jpg
http://localhost:8080/image3.jpg
http://localhost:8080/image4.jpg
Springboot会默认去三个目录下去寻找静态资源,均能访问到

image.png


如果我们新建一image文件夹并添加图片
http://localhost:8080/image1.jpg就访问不到了,因此我们需要如下方式修改

 

第一种方式

拦截器重定向,继承WebMvcConfigurerAdapter类重写addResourceHandlers接口


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorRegister extends WebMvcConfigurerAdapter{

    private static final Logger logger = LoggerFactory.getLogger(InterceptorRegister.class);

    /*
     * 注册静态文件的自定义映射路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //定义到新文件夹
        registry.addResourceHandler("/image/**")
                .addResourceLocations("classpath:/image/");
        //定义到硬盘
        registry.addResourceHandler("/picture/**")
                .addResourceLocations("file:D:/picture/");
        super.addResourceHandlers(registry);
    }
}

添加新的image路径及图片image.jpg

http://localhost:8080/image/image1.jpg

image.png

 

运行,访问picture,就会发现可以访问硬盘文件了

http://localhost:8080/picture/image5.jpg

image.png

 

第二种方式

配置文件配置参数

#静态资源设定,添加此参数将覆盖默认的 src/resources/public  src/resources/static  src/resources/resources 三个路径,所以需要重新定义
disk-path=D:/picture/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${disk-path}

直接访问图片,就能访问到硬盘文件

http://localhost:8080/image5.jpg

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值