配置本地资源映射路径 addResourceHandlers

本文介绍了如何在Spring MVC中通过实现WebMvcConfigurer接口,配置addResourceHandlers来映射本地资源路径,以实现静态文件的访问。关键在于addResourceLocations添加的真实路径末尾必须加上'/',否则将无法正确映射。作者通过举例展示了具体的配置代码,并分享了解决此问题的经验。

配置本地资源映射路径 addResourceHandlers

实现 WebMvcConfigurer,重写addResourceHandlers(ResourceHandlerRegistry registry)方法
addResourceHandler() 添加的是访问路径
addResourceLocations()添加的是映射后的真实路径,映射的真实路径末尾必须加 / ,不然映射不到,这个问题困扰了我半天, / 适用于 windows和linux
如下:

package cn.mindgd.config;


import org.springframework.context.annotation.Bean;
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.WebMvcConfigurer;

/**
 * 拦截器配置
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    /**
     * @author: JiaXinMa
     * @description: 访问静态文件
     * @date: 2021/4/15
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //访问路径
        registry.addResourceHandler("/api/upload/**")
                //映射真实路径
                .addResourceLocations("file:" + System.getProperty("user.dir") + "/");//必须加"/",不然映射不到  
    }
}

System.getProperty(“user.dir”) 是当前项目路径
在这里插入图片描述
成功访问如下:
在这里插入图片描述
想看更多精彩内容,可以关注我的博客园
我的博客园

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值