Using environment vars in java applications

This is a common question from people starting with java and j2ee: “how can i use environment variables in my programs, which can be set by the administrator at deploy time?” Here’s a small example how you can achieve this, and how the administrator can set the value of an environment variable after deployment.

Here’s an example jsp page, which gets the value of an environment variable called jndi-password:

<%@ page contentType="text/html;charset=windows-1252"
	 import="javax.naming.*"%>
<html>
  <head>
	<meta http-equiv="Content-Type"
	      content="text/html; charset=windows-1252">
	<title>untitled</title>
  </meta></head>
  <body>
  < %
   Context initial = new InitialContext();
	  Context environment =
	    (Context)initial.lookup("java:comp/env");

	String password =
	  (String)environment.lookup("jndi-password");
  %>
  < %=password %>
  </body>
</html>

You have to define your environment variables in the web.xml file like this:

<?xml version = '1.0' encoding = 'windows-1252'?>
<!DOCTYPE web-app PUBLIC
	"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
	"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <description>Jsp app using env entry</description>
  <env-entry>
	<description>Password for jndi</description>
	<env-entry-name>jndi-password</env-entry-name>
	<env-entry-value>mypass</env-entry-value>
	<env-entry-type>java.lang.String</env-entry-type>
  </env-entry>
</web>

After you deploy this example, the administrator can overwrite the default value of jndi-password in oc4j’s enterprise manager:

Settings j2ee environment variables in oc4j

blog comments powered by Disqus