项目打包后获取文件的问题

1.问题背景
题主遇到的这个问题主要是需要对API中录入富文本内容做xss攻击校验,采用的是AntiSamy的第三方依赖,需要引入一个策略.xml文件,在本地IDEA无论使用Resource类还是使用Classpathresource类获取文件均无问题,但是在打成jar发布到测试环境后 使用Resource类无法获取到文件,而使用Classpathresource则无问题。(以下问题的复现,是在工作期间使用公司的windows的小本本,本地打包复现的)
2.报错异常

org.owasp.validator.html.PolicyException: java.io.FileNotFoundException: D:\projects\demo\target\file:\D:\projects\demo\target\demo-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\antisamy-anythinggoes.xml (文件名、目录名或卷标语法不正确。)

3.分析问题原因
一般来说, 程序运行所必须的资源文件我们会一起打包到 jar. 那么接下去我们就要读取这个资源文件.在集成环境和生产环境上, 我们的程序是一个jar包而不是exploded方式, 也就是说, 此时的new DefaultResourceLoader().getResource("classpath:antisamy-anythinggoes.xml") 将有不一样的行为.我们在 IDEA 调试的时候, 资源文件是存在于真实文件系统里的一个文件. 而在jar包中, 它不是一个真实文件系统的文件.为了能用统一的文件系统路径去表示jar内的文件, Java开创了 ! 这个符号.! 表示这个文件是一个压缩包(zip)(jar 本身就是一个 zip), 之后的路径则为压缩包内的路径(压缩包内的路径不分运行平台, 统一为 Unix 路径).正常情况下的 new DefaultResourceLoader().getResource("classpath:antisamy-anythinggoes.xml") 操作, 会得到一个 jar包路径后面加上一个!号然后再拼接上包内路径的一个路径.Spring Boot为了避免资源文件冲突(Java的打包规范忽略了资源文件的问题, 两个库的代码文件是可以合并的, 因为包名不同. 但是资源文件都从jar的根目录开始编排, 如果重名将互相覆盖而导致打包后资源文件的丢失)而采用 fat-jar 的方式来打包程序.fat-jar 就是一种 nested jar, 所有的依赖库不会合并到用户代码上, 而是以jar包的形式存放在jar包内,一个典型的springboot打完包的结构大概是这样的

META-INF
    MANIFEST.MF
org
    springframework
        boot
            loader
                (Launcher)
BOOT-INF
    classes
        (user code)
    lib
        dependence.jar

jar的入口类其实是Spring Boot Launcher,他会为每一个依赖创建一个ClassLoader, 这样就可以让每个依赖自己读取自己的资源文件而互不冲突.而用户自己的类是从/BOOT-INF/classes开始的, 用户自己的资源文件的根目录也在这里, 所以为了让用户能够正确读到自己的资源文件. 加载用户代码的那个 ClassLoader 的 classpath 从这里开始.fat-jar并不是 Java官方标准, 所以 Java 认为所有 classpath 都是从 jar 的根目录开始的.于是我们得到的文件路径, 将是 {用户代码根目录}!/{资源文件路径}而用户代码根目录本身就是在jar内的, 最终我们会得到这么一个路径jar:D:\projects\demo\target\file:\D:\projects\demo\target\demo-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\antisamy-anythinggoes.xml(注意,有两个!号)没错, classes文件夹被认为是一个压缩包了.所以我们将找不到这个文件.如果读取资源文件的操作只在自己的代码发生, 那么只要不使用new DefaultResourceLoader().getResource("classpath:antisamy-anythinggoes.xml")而直接获取流就可以避免这个问题. 但是很多情况下, 并非自己要读文件, 而是第三方库要读文件.例如第三方库可能会要求在配置文件中配置key文件的路径, 而这个路径支持网络读取, 所以必须是URI. 然后第三方库的代码中就会使用new DefaultResourceLoader().getResource("classpath:antisamy-anythinggoes.xml")来获取文件路径,再去读它,这样以获取文件, 就抛出异常了.
4.解决方案
方案一:使用ClassPathResource替换Resource

package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

@RestController
@Slf4j
public class Test {
    private static ResourceLoader resourceLoader = new DefaultResourceLoader();


    /**
     * 使用 ClassPathResource 完美获取jar中的文件
     */
    @RequestMapping(value = "/clean-html-by-classpath-resource", method = RequestMethod.GET)
    public String cleanHtmlByClassPathResource(@RequestParam(value = "sourceStr",
            defaultValue = "<img onerror='alert(123)'>") String sourceStr) {
        log.info("start clean html by class path resource,the source str is:{}", sourceStr);
        String targetStr = "";
        try {
            ClassPathResource classPathResource = new ClassPathResource("antisamy-anythinggoes.xml");
            InputStream inputStream = classPathResource.getInputStream();
            Policy policy = Policy.getInstance(inputStream);
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(sourceStr, policy);
            targetStr = cr.getCleanHTML();
        } catch (Exception e) {
            log.error("clean html by class path resource,the error is:{}", e);
        }
        log.info("finish clean html by class path resource,the target str is:{}", targetStr);
        return targetStr;
    }

    /**
     * 使用 Resource 无法获取jar中的文件
     */
    @RequestMapping(value = "/clean-html-by-resource")
    public String cleanHtmlByResource(@RequestParam(value = "sourceStr",
            defaultValue = "<img onerror='alert(123)'>") String sourceStr) {
        log.info("start clean html by resource,the source str is:{}", sourceStr);
        Resource resource = resourceLoader.getResource("classpath:antisamy-anythinggoes.xml");
        String targetStr = "";
        String xmlPath;
        try {
            xmlPath = resource.getURL().getPath();
            Policy policy = Policy.getInstance(xmlPath);
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(sourceStr, policy);
            targetStr = cr.getCleanHTML();
        } catch (Exception e) {
            log.error("clean html by resource,the error is:{}", e);
        }
        log.info("finish clean html by resource,the target str is:{}", targetStr);
        return targetStr;
    }
}

方案二:https://github.com/ulisesbocchio/spring-boot-jar-resources

全部评论

相关推荐

ming_ri:“很抱歉,您的简历和我们当前的职位需求不是很匹配”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务