h1

Putting properties in the web xml file

January 25, 2011

If you are building a web app in Java or Scala, you might want to feed in a variable from outside which describes something special about the particular environment the web app is running on.  On a normal application you might do this from the command line with a command line argument.  In a web app, you put the variables in the web.xml file. In a maven built project this can be found in /src/main/java/webapp/WEB-INF/web.xml

The XML for the variable looks like this …

<env-entry>
<env-entry-name>PROPS_FOLDER</env-entry-name>
<env-entry-value>/opt/webapp/properties</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>

In your code, the property can be accessed by any class which extends HttpServlet. The following imports are therefore required:

import javax.servlet.http.HttpServlet;
import javax.naming.Context;
import javax.naming.InitialContext;

The property can then be accessed in your Java code like this:

Context env = (Context) (new InitialContext().lookup("java:comp/env"));
String PROPS_FOLDER = (String) env.lookup("PROPS_FOLDER");

And in Scala like this:

val env:Context = (new InitialContext().lookup("java:comp/env")).asInstanceOf[Context];
val PROPS_FOLDER:String = env.lookup("PROPS_FOLDER").asInstanceOf[String];
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: