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 ?
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 :-)
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With