簡體   English   中英

如何從servlet上下文中的jar文件中讀取xml模式

[英]How to read xml schema from jar file in a servlet context

我有一個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中是更好的解決方案,以確保libs和模式版本適合。

你有什么想法嗎?

提前致謝:

吉姆

分配

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

public static String getPath(String path){
  return UtilityClass.class.getResource(path).toString();
}

問題是您的servlet應用程序正在/沒有文件的地方查找文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM