SpringBoot虚拟路径映射

要求:访问:127.0.0.1/image/下的文件时,自动映射到真实路径:D:Files\。

复制代码
virtualFileDepositPath: /image/**
realityFileDepositPath: C:\Users\xin\Desktop\imgCreate\Files\
java 复制代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 图片绝对地址与虚拟地址映射
 */

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Value("${realityFileDepositPath}")
    private String realityFileDepositPath;

    @Value("${virtualFileDepositPath}")
    private String virtualFileDepositPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(virtualFileDepositPath)
                .addResourceLocations("file:" + realityFileDepositPath);
    }
}

这个Java类和重写的addResourceHandlers方法是用来实现Spring MVC中的虚拟路径映射功能的。

具体来说:

  1. 这个类继承了WebMvcConfigurerAdapter,这是一个Spring MVC的配置适配器类。
  2. 重写了addResourceHandlers方法,这个方法用来配置静态资源的处理。
  3. 在方法中,使用了registry.addResourceHandler来关联一个虚拟路径virtualFileDepositPath和一个实际磁盘路径realityFileDepositPath。
  4. 这样就实现了一个虚拟路径到实际磁盘路径的映射。
  5. 当外部用户访问虚拟路径时,会被映射到实际磁盘路径去查找资源。
  6. 这样可以隐藏真实文件的磁盘位置,并可以灵活重新组织文件目录结构。
  7. 对外部用户来说,只需要访问不变的虚拟路径就可以访问到文件资源,无需关心实际存放位置。

总之,这个类实现了Spring MVC中虚拟路径映射的功能,通过配置可以映射虚拟路径到实际磁盘路径,从而隐藏具体文件位置,改善外部访问方式。

相关推荐
青山木1 分钟前
Hot 100 --- 划分字母区间
java·数据结构·算法·leetcode·贪心算法
Zzzzmo_4 分钟前
SpringBoot 配置文件
java·spring boot
君顾19 分钟前
外卖CPS小程序开发实战指南:从零到上线的完整流程
java·开发语言·外卖
無a伟9 分钟前
RabbitMq高级特性:消息确认,持久化,重试机制
java·分布式·rabbitmq
明月_清风11 分钟前
Foundry Cheatcode 详解:prank、warp、deal、expectRevert、expectEmit
后端·web3·solidity
流烟默19 分钟前
xxl-job 接入 Spring 的两种方式:手动装配与自动装配(含 initMethod 双启动踩坑实录)
java·spring·xxl-job
鹅城剑仙20 分钟前
Spring Boot 3 全局异常处理与统一响应封装进阶实战
java·spring boot·后端
明月_清风25 分钟前
Foundry Fuzz Testing:让测试自动寻找 Solidity Bug
后端·web3·solidity
橘子汽水16833 分钟前
Leetcode 208,207实现Trie前缀树,课程表
java·数据结构·算法·leetcode
IT_陈寒35 分钟前
SpringBoot自动配置失效时我差点把电脑扔了
前端·人工智能·后端