在 java class 中读取 web.xml 的值

Read the value from web.xml in a java class

我有一个 Web 应用程序,其中包含一个 web.xml 文件和一些 java class 我用 Maven 构建的文件。在某些时候,我想在 java class 中获取 web.xml 文件中的一个参数。

如何在普通 java class 而不是 Servlet 中读取值?

您可以使用 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");

获取属性

您可以使用 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

像这样在您的 web.xml 中添加一个初始化参数 -

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

您可以使用 -

在您的代码中访问它
getServletContext().getInitParameter("myParam")

我找到了解决方案,实际上你必须像这样在 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 class 中,您必须导入 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");

希望这对其他人也有帮助:-)

我也遇到过类似的挑战;我不会详细介绍,但足以说明我试图规避使用环境变量来设置 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;
}

更简单:

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 class:

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