Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the value from web.xml in a java class

Tags:

java

web.xml

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 ?

like image 880
Sebastian Avatar asked Apr 06 '16 09:04

Sebastian


2 Answers

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

like image 64
Sebastian Avatar answered Oct 23 '22 19:10

Sebastian


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");
like image 22
Somebody Avatar answered Oct 23 '22 17:10

Somebody