Use JNDI to look up Java components

To access some Java objects (such as enterprise beans, 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, 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 an enterprise bean

The code snippet that follows shows a lookup of an enterprise bean's home interface. The actual lookup name of this interface is determined by the application's deployment descriptors.

AccountHome accountHome = null;
try {
   java.lang.Object ejbHome = initialContext.lookup("java:comp/env/ejb/accounting");
   accountHome = (AccountHome)javax.rmi.PortableRemoteObject.narrow(ejbHome, AccountHome.class);
}
catch (NamingException e) { 
   // Error getting the home interface
   // ... error-handling code ...
}

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. Use the WAS 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, beans, 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 ...
}