从 java 类中的 web.xml 读取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36446663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:27:50  来源:igfitidea点击:

Read the value from web.xml in a java class

javaweb.xml

提问by Sebastian

I have a Web Application with a web.xml file and some java classes that I build with Maven. At some point I want to get in the java class a parameter from the web.xml file.

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

How can I read the value in a normal java class, not a Servlet ?

如何读取普通 java 类而不是 Servlet 中的值?

回答by Sebastian

I found the solution for this and actually you have to declare some env-entry tags in the web.xml like this :

我找到了解决方案,实际上你必须在 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>

In your java class you have to import the Context and NamingException (this was in my case, i am not sure if this applies to others) :

在您的 java 类中,您必须导入 Context 和 NamingException (这是在我的情况下,我不确定这是否适用于其他人):

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

and where you want to get the value you must do it like this :

以及您想要获得价值的地方,您必须这样做:

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

Hopefully this helps others too :-)

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

回答by Sampada

Add an init-param in your web.xml like this -

像这样在 web.xml 中添加一个 init-param -

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

You can access this in your code using -

您可以使用 - 在您的代码中访问它

getServletContext().getInitParameter("myParam")

回答by Somebody

Even simpler:

更简单:

web.xml:

网页.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:

java类:

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

回答by Sandeep Sukhija

You can read the XML file using the Properties object.

您可以使用 Properties 对象读取 XML 文件。

Sample code on how to load the xml is mentioned below:

下面提到了有关如何加载 xml 的示例代码:

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

Once the file is loaded, now you can fetch the properties using properties.getProperty("keyname");

加载文件后,现在您可以使用获取属性 properties.getProperty("keyname");

回答by Hodglem

I had a similar challenge; I won't go into detail but suffice it to say that I was trying to circumvent having an environment variable to set logback logging paths. This isn't the solution I went with, but it does locate and read in web.xml and allows you to grab variables. It uses JDOM2 so you could pretty much read whatever you wanted.

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

回答by nyname00

You can use XPathto find the element you're interested in, e.g.

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

Edit: based on your comments, here' a way to get the file handle to your web.xml. Note that, without a ServletContextit depends on from where you are calling this. So this might not work in your case, but you can tweak it to get the file.

编辑:根据您的评论,这是一种获取web.xml文件句柄的方法。请注意,如果没有 a,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