Write the J2EE application client

A J2EE application client program operates similarly to a standard Java program. It runs its own Java virtual machine and is invoked with its main() method. The Java virtual machine application client program differs from a standard Java program because it uses the Java Naming and Directory Interface (JNDI) name space to access resources.

For information on how to access data from J2EE application clients, see Access data from J2EE application clients.

In a standard Java program, the resource information is coded into the program. Because the resource information is separate from the client application program, the client application program is portable and more flexible.

Use the javax.naming.InitialContext class, the client application program uses the lookup operation to access the JNDI name space. The InitialContext class provides the lookup method to locate resources.

This example illustrates how a client application program uses the InitialContext class:

import javax.naming.*

public class myAppClient
{
  public static void main(String argv[])
  {
    InitialContext initCtx = new InitialContext();
    Object homeObject = initCtx.lookup("java:comp/env/ejb/BasicCalculator");
    BasicCalculatorHome bcHome = (BasicCalculatorHome)
       javax.rmi.PortableRemoteObject.narrow(homeObject, BasicCalculatorHome.class); 
    BasicCalculatorHome bc = bcHome.create();
     ...
  }
}

See the Code example disclaimer for legal information about this code example.

In this example, the program looks up an enterprise bean called BasicCalculator. The BasicCalculator EJB reference is located in the client JNDI name space at java:comp/env/ejb/BasicCalculator. Because the actual enterprise bean runs on the server, the application client run time returns a reference to the BasicCalculator home interface.

If the client application program lookup was for a resource reference or an environment entry, then the lookup returns an instance of the configured type (as defined by the client application deployment descriptor). For example, if the program lookup was a JDBC datasource, the lookup would return an instance of javax.sql.DataSource.