SpringBoot virtual path mapping

Requirement: When accessing files under: 127.0.0.1/image/, it is automatically mapped to the real path: D:Files\.

virtualFileDepositPath: /image/**
realityFileDepositPath: C:\Users\xin\Desktop\imgCreate\Files\
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);
    }
}

This Java class and the overridden addResourceHandlers method are used to implement the virtual path mapping function in Spring MVC.

Specifically:

  1. This class inherits WebMvcConfigurerAdapter, which is a Spring MVC configuration adapter class.
  2. The addResourceHandlers method has been rewritten, which is used to configure the processing of static resources.
  3. In the method, registry.addResourceHandler is used to associate a virtual path virtualFileDepositPath and an actual disk path realityFileDepositPath.
  4. This achieves a mapping of a virtual path to an actual disk path.
  5. When external users access the virtual path, it will be mapped to the actual disk path to find resources.
  6. This can hide the disk location of real files and flexibly reorganize the file directory structure.
  7. For external users, they only need to access the unchanged virtual path to access file resources without caring about the actual storage location.

In short, this class implements the virtual path mapping function in Spring MVC. Through configuration, the virtual path can be mapped to the actual disk path, thereby hiding the specific file location and improving external access methods.

 

おすすめ

転載: blog.csdn.net/LYXlyxll/article/details/132612916