Read the value from web.xml in a java class

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


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

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

Tags:

Java

Web.Xml