blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

Bind and lookup wrapper objects using env-entry : tomcat


In most of the applications, environment specific configurations are store in either a properties file or in web.xml.

Advantages of using env-entries are:

  • You don't have to create a properties file since you specify it in web.xml.
  • Env-entries are initialized automatically when the application starts.
  • Env-entries are available through JNDI.


Disadvantages:

  • You have to write xml(not as easy as properties).
  • Cannot use custom classes (possible using resource-env-ref)
  • Values are tightly bound within the web app (Using resource-env-ref values are specified outside)


Java EE 6 supported types are limited to the following:
  1. java.lang.String
  2. java.lang.Integer
  3. java.lang.Short
  4. java.lang.Float
  5. java.lang.Double
  6. java.lang.Byte
  7. java.lang.Character
  8. java.lang.Boolean
  9. java.lang.Class
  10. java.lang.Enum (any enum)


Let's try to store a variable "isConnected" with a boolean value.

Declare in your web application's web.xml:


<env-entry>
<description>Sample env entry</description>
<env-entry-name>isConnected</env-entry-name>
<env-entry-type>java.lang.Boolean</env-entry-type><!--order matters -->
<env-entry-value>true</env-entry-value>
</env-entry>

And in your java code,
try {
 Context initCxt =  new InitialContext();
 Boolean isConn =  (Boolean)initCxt.lookup("java:comp/env/isConnected");
 System.out.println(isConn.toString());
 // one could use relative names into the sub-context
 Context envContext = (Context) initCxt.lookup("java:comp/env");
 Boolean isConn2 = (Boolean)envContext.lookup("isConnected");
 System.out.println(isConn2.toString());
} catch (NamingException e) {
 e.printStackTrace();
}

Output:
true

Continue reading: Bind and lookup beans using resource-env-ref (tomcat)

1 comment: