Read the value from web.xml in a java class
Asked Answered
W

6

9

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.

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

Ways answered 6/4, 2016 at 9:16 Comment(4)
do you want to read context - param or init-param from the web.xml ?Antakiya
@VikrantKashyap does not matter as long as I can add a parameter in that xml file and receive it in my java class. What I want to do is that I want to create multiple war files and I edit this web.xml based on some configurations. I want to add a parameter in this web.xml and send it to the java class when the build happens. Thank you for your answerWays
@Sebastian, you wrote I want to add a parameter in this web.xml and send it to the java class when the build happens .. So does it mean, you want to read the xml file during the build time and not during the run time.Boyla
@SandeepSukhija I want to read the xml file at run time. ThxWays
W
13

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

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

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

Ways answered 6/4, 2016 at 13:19 Comment(1)
Can you please explain how you read the properties? Now that the fileName is a string, so just wanted to know the continuation where you read the prop from prop file in the code. Also, what is link to the property file? Is it the one specified in env-entry-value?Fred
S
2

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

<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")
Stricken answered 6/4, 2016 at 10:36 Comment(1)
thank you for your answer but I can't use Servlets, I must use a normal Java ClassWays
F
2

Even simpler:

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");
Fugato answered 13/2, 2019 at 14:34 Comment(0)
B
0

You can read the XML file using the Properties object.

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

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");

Boyla answered 6/4, 2016 at 9:48 Comment(3)
@nyname00 can you please elaborate, why will it not work?Boyla
Reading an XML file with Properties.loadFromXml requires a special format, including a <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> ... which a standard web.xml file will not haveRotterdam
@SandeepSukhija thank you for your answer but I can't use this solution because that would mean I would have to use a hard-coded path for the xml file and I can't do that.Ways
R
0

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

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 ServletContext it 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.

 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
Rotterdam answered 6/4, 2016 at 10:27 Comment(1)
@Ways You can run the code from anywhere you want, you just need to provide the file handle. From your original post it was unclear which element you wanted to read, so I decided to use the servlet name for my example.Rotterdam
C
0

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.

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;
}
Cruse answered 15/6, 2018 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.