Use JNDI to look up Java components

To access some Java objects (such as data sources, or JavaMail sessions) in a distributed computing environment, you can use the JNDI API. These Java objects are sometimes referred to as enterprise resources.

Before you can access an enterprise resource in a JNDI environment, you must first obtain the initial JNDI context for the component. The examples that follow assume that you have already written code to obtain the initial context, which is represented by the object name initialContext:

Example: Look up a data source

The DataSource object is defined in the JDBC 2.0 Optional Package. The actual name to lookup is defined by the JNDI Name property for the DataSource object. You can use the Websphere administrative console to view this property. For example, if you have a DataSource object named AccountDataSource, the JNDI name for that DataSource would be java:comp/env/jdbc/AccountDataSource.

try {
   DataSource ds = (DataSource)initialContext.lookup("java:comp/env/jdbc/AccountDataSource");
}
catch (NamingException e) { 
   // Error getting the data source object
   // ... error-handling code ...
}

Example: Look up a JavaMail session

The actual name to look up is defined in the deployment descriptor of the Web application that contains your servlets or JSP files that use the JavaMail API.

try {
   Session session = (Session)initialContext.lookup("java:comp/env/mail/MailSession")
}
catch (NamingException e) { 
    // Error getting the mail session
   // ... error-handling code ...
}