【问题标题】:How to read xml schema from jar file in a servlet context如何在 servlet 上下文中从 jar 文件中读取 xml 模式
【发布时间】:2011-07-11 02:32:56
【问题描述】:

我有一个 Maven 库项目,其中包含一些处理 xml 消息的类。每当我收到其中一条消息时,我都会使用我编写的 xml 模式文件对其进行验证。为我进行验证的代码如下所示:

public static Document parseXML(final String xml) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true);
    builder.setFeature("http://apache.org/xml/features/validation/schema", true);
    URL location = CMPMessage.getClass().getResource(XML_SCHEMA_LOCATION);
    if (null == location) {
        throw new IOException("Unable to load schema definition file.");
    }
    builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
            "http://www.mycompany.de/MyProtocol " + location);
    return builder.build(new StringReader(xml));
}

XML_SCHEMA_LOCATION是这样的:

private static final String XML_SCHEMA_LOCATION = "/ConvertMessageProtocol.xsd";

.xsd 文件位于src/main/resources 中,并且感谢 maven,一切正常:当告诉 maven 制作一个包时,.xsd 文件被包含在 .jar 中。 我做了一个简单的测试项目来检查 .xsd 文件是否真的会被找到。源代码如下所示:

import java.io.IOException;
import org.jdom.JDOMException;
import de.mycomp.MyMessage;


public class Main {
    public static void main(final String[] args) {
        try {
            MyMessage.parseXML(args[0]);
        }
        catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

是的,xml 将使用架构文件进行验证。

现在来了:我想在 servlet 中使用我的小库(在 tomcat 中运行),但是在那里找不到 .xsd 文件:(

当然,我可以将 .xsd 文件存储在其他地方,例如直接在公司服务器上并通过 http 检索它,但我认为将其包含在 .jar 中是确保库和架构版本的更好解决方案适合。

你有什么想法吗?

提前致谢:

吉姆

【问题讨论】:

    标签: java xml servlets jar schema


    【解决方案1】:

    分配

    private static final String XML_SCHEMA_LOCATION = getPath("/ConvertMessageProtocol.xsd");
    
    public static String getPath(String path){
      return UtilityClass.class.getResource(path).toString();
    }
    

    问题是您的 servlet 应用程序正在寻找没有文件的 / 文件。

    【讨论】:

    • 非常感谢您的快速答复。但要么我不明白,要么我没有说清楚:XML_SCHEMA_LOCATION 和对getResource 的调用都在同一个MyMessage 类中。
    • 在您的 jar 文件中,您正在使用 private static final String XML_SCHEMA_LOCATION = "/ConvertMessageProtocol.xsd";/ 读取配置文件,现在您已经在 Web 应用程序中添加了该 jar,所以现在 / 与您需要的不同现在把它当作资源。要么使用上述方法,要么将private static final String XML_SCHEMA_LOCATION = "/ConvertMessageProtocol.xsd"; 替换为"classpath:ConvertMessageProtocol.xsd";
    • 是的,非常感谢,我花了几个小时才找到解决方案。我用 getPath 方法尝试了第一个,它可以工作。
    猜你喜欢
    • 2013-03-15
    • 2011-04-09
    • 2011-01-17
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多