springboot 配置静态本地映射资源访问路径加密

springboot 配置静态本地映射资源访问路径加密

  • 配置静态本地映射资源访问

配置静态本地映射资源访问

SpringBoot 配置一个本地资源目录映射地址,就可通过 http://localhost:8082/file/文件相对路径 访问图片

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(/file/**”).addResourceLocations("file:D:/dome/");
    }
}

需求: 让 请求地址 文件相对路径 以一种加密不可读的方式展示请求。如:
正常访问:http://localhost:8082/file/group//application//business//type//090821//bi.jpg
加密访问:http://localhost:8082/file/6f5e030e338f5eadb8108f370e8067144f9132aceac9c5feaa66ea62ae269ad27b26969dfd60ebfd75ffd9312c540bab

Code:
使用拦截器解码请求路径,重置request访问的图片相对路径地址

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FileHandlerInterceptor()).addPathPatterns(DemoUtil.URL_PATH);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(DemoUtil.URL_PATH).addResourceLocations("file:" + DemoUtil.PATH);
    }
}
public class FileHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE,
                DemoUtil.decrypt((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)));
        return true;
    }
}

加解密 hutool 工具类

public class DemoUtil {
    public static final String URL_PATH = "/file/**";
    public final static String PATH = "D:/uploadFiles/";

    private final static AES AES = SecureUtil.aes(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());

    public static String encrypt(String inStr) {
        return AES.encryptHex(inStr);
    }

    public static String decrypt(String str) {
        return AES.decryptStr(str);
    }
}

测试结果:
springboot 配置静态本地映射资源访问路径加密_第1张图片
案例代码地址

你可能感兴趣的:(java,java)