簡體   English   中英

從java類中的web.xml讀取值

[英]Read the value from web.xml in a java class

我有一個帶有web.xml文件的Web應用程序和一些我用Maven構建的java類。 在某些時候,我想從java.xml類中獲取web.xml文件中的參數。

如何讀取普通java類中的值,而不是Servlet?

我找到了解決方案,實際上你必須在web.xml中聲明一些env-entry標簽,如下所示:

<env-entry> 
    <env-entry-name>properties-file</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>Property</env-entry-value> 
</env-entry>

在你的java類中你必須導入Context和NamingException(這是我的情況,我不確定這是否適用於其他人):

    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;

如果你想獲得價值,你必須這樣做:

    Context ctx = new InitialContext();
    Context env = (Context) ctx.lookup("java:comp/env");
    final String fileName = (String) env.lookup("properties-file");

希望這也有助於其他人:-)

在你的web.xml中添加一個init-param,如下所示 -

<init-param>
   <param-name>myParam</param-name>
   <param-value>myParamValue</param-value>
  </init-param>

您可以使用以下代碼訪問代碼:

getServletContext().getInitParameter("myParam")

更簡單:

web.xml中:

<env-entry> 
    <env-entry-name>properties-file</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>Property</env-entry-value> 
</env-entry>

java類:

InitialContext initialContext = new InitialContext();
String fileName = (String) initialContext.lookup("java:comp/env/properties-file");

您可以使用Properties對象讀取XML文件。

有關如何加載xml的示例代碼如下所述:

File file = new File("test.xml");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.loadFromXML(fileInput);
fileInput.close();

加載文件后,現在可以使用properties.getProperty("keyname");獲取屬性properties.getProperty("keyname");

我有類似的挑戰; 我不會詳細說明,但足以說我試圖繞過設置環境變量來設置logback日志記錄路徑。 這不是我使用的解決方案,但它確實在web.xml中定位和讀取並允許您獲取變量。 它使用JDOM2,因此您幾乎可以閱讀任何想要的內容。

private String getLogLocation() throws JDOMException, IOException {
     SAXBuilder jdomBuilder = new SAXBuilder();
     String logLocation = null;

     Document jdomDocument = jdomBuilder.build(this.getFilePath());
     Element webXMLRoot = jdomDocument.getRootElement();
     List<Element> elements = webXMLRoot.getChildren();

    for (Element e : elements) {

        for (Element childElement : e.getChildren()) {
        System.out.println(childElement.getQualifiedName());
         if (childElement.getValue().equals("logLocation")) {
             logLocation = e.getChild("env-entry-value",childElement.getNamespace()).getValue();
        break;
    }
    }

}



return logLocation;
}

private String getFilePath() {
String classPath = LoggerStartupListener.class.getProtectionDomain().getCodeSource().getLocation().getPath();
classPath = classPath.replace("classes", "");
classPath = classPath + "web.xml";
return classPath;
}

您可以使用XPath來查找您感興趣的元素,例如

DocumentBuilder builder = DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder();

Document doc = builder.parse(file);
XPath xpath = XPathFactory
    .newInstance()
    .newXPath();

XPathExpression expr = xpath.compile("/web-app/servlet/servlet-name[text()='MyServlet']");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

編輯 :根據您的評論,這里是一種獲取web.xml文件句柄的方法。 請注意,沒有ServletContext它取決於您調用它的位置。 所以這可能不適用於你的情況,但你可以調整它來獲取文件。

 File clsLocation = new File(getClass()
        .getProtectionDomain()
        .getCodeSource()
        .getLocation()
        .getFile());
 String webXml = clsLocation
        .getCanonicalPath()
        .replaceAll("WEB-INF.*", "WEB-INF/web.xml");
 File file = new File(webXml);
 // use 'file' with the code above and change the XPath to the element you want to read

暫無
暫無

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

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