The J2EETM Tutorial
Home
TOC
Index
PREV TOP NEXT Search
Feedback

The CartEJB Example

The CartEJB session bean represents a shopping cart in an online bookstore. The bean's client may add a book to the cart, remove a book, or retrieve the cart's contents. To construct CartEJB, you need the following code:

All session beans require a session bean class. All enterprise beans that permit remote access must have a home and remote interface. To meet the needs of a specific application, an enterprise bean may also need some helper classes. The CartEJB session bean uses two helper classes, BookException and IdVerifier, which are discussed in the section Helper Classes.

The source code for this example is in the j2eetutorial/examples/src/ejb/cart directory. To compile the code, go to the j2eetutorial/examples directory and type ant cart. A sample CartApp.ear file is in the j2eetutorial/examples/ears directory.

Session Bean Class

The session bean class for this example is called CartBean. Like any session bean, the CartBean class must meet these requirements:

The source code for the CartBean class follows.

import java.util.*;	
import javax.ejb.*;	
	
public class CartBean implements SessionBean {	
	
   String customerName;	
   String customerId;	
   Vector contents;	
	
   public void ejbCreate(String person) throws CreateException {	
	
      if (person == null) {	
        throw new CreateException("Null person not allowed.");	
      }	
      else {	
         customerName = person;	
      }	
	
      customerId = "0";	
      contents = new Vector();	
   }	
	
   public void ejbCreate(String person, String id) 	
     throws CreateException {	
	
      if (person == null) {	
        throw new CreateException("Null person not allowed.");	
      }	
      else {	
         customerName = person;	
      }	
	
      IdVerifier idChecker = new IdVerifier();	
      if (idChecker.validate(id)) {	
         customerId = id;	
      }	
      else {	
         throw new CreateException("Invalid id: "+ id);	
      }	
	
      contents = new Vector();	
   }	
	
   public void addBook(String title) {	
	
      contents.addElement(title);	
   }	
	
   public void removeBook(String title) throws BookException {	
	
      boolean result = contents.removeElement(title);	
      if (result == false) {	
         throw new BookException(title + "not in cart.");	
      }	
   }	
	
   public Vector getContents() {	
      return contents;	
   }	
	
   public CartBean() {}	
   public void ejbRemove() {}	
   public void ejbActivate() {}	
   public void ejbPassivate() {}	
   public void setSessionContext(SessionContext sc) {}	
	
} 
 

The SessionBean Interface

The SessionBean interface extends the EnterpriseBean interface, which in turn extends the Serializable interface. The SessionBean interface declares the ejbRemove, ejbActivate, ejbPassivate, and setSessionContext methods. The CartBean class doesn't use these methods, but it must implement them because they're declared in the SessionBean interface. Consequently, these methods are empty in the CartBean class. Later sections explain when you might use these methods.

The ejbCreate Methods

Because an enterprise bean runs inside an EJB container, a client cannot directly instantiate the bean. Only the EJB container can instantiate an enterprise bean. During instantiation, the example program performs the following steps.

  1. The client invokes a create method on the home object:
    Cart shoppingCart = home.create("Duke DeEarl","123");
     
    
  2. The EJB container instantiates the enterprise bean.
  3. The EJB container invokes the appropriate ejbCreate method in CartBean:
     public void ejbCreate(String person, String id) 	
       throws CreateException {	
    	
       if (person == null) {	
         throw new CreateException("Null person not allowed.");	
       }	
       else {	
          customerName = person;	
       }	
    	
       IdVerifier idChecker = new IdVerifier();	
       if (idChecker.validate(id)) {	
          customerId = id;	
       }	
       else {	
          throw new CreateException("Invalid id: "+ id);	
       }	
    	
       contents = new Vector();	
    }
     
    

Typically, an ejbCreate method initializes the state of the enterprise bean. The preceding ejbCreate method, for example, initializes the customerName and customerId variables with the arguments passed by the create method.

An enterprise bean must have one or more ejbCreate methods. The signatures of the methods must meet the following requirements:

The throws clause may include the javax.ejb.CreateException and other exceptions that are specific to your application. The ejbCreate method usually throws a CreateException if an input parameter is invalid.

Business Methods

The primary purpose of a session bean is to run business tasks for the client. The client invokes business methods on the remote object reference that is returned by the create method. From the client's perspective, the business methods appear to run locally, but they actually run remotely in the session bean. The following code snippet shows how the CartClient program invokes the business methods:

Cart shoppingCart = home.create("Duke DeEarl", "123");	
. . .	
shoppingCart.addBook("The Martian Chronicles"); 	
shoppingCart.removeBook("Alice In Wonderland");	
bookList = shoppingCart.getContents();
 

The CartBean class implements the business methods in the following code:

public void addBook(String title) {	
	
   contents.addElement(new String(title));	
}	
	
public void removeBook(String title) throws BookException {	
	
   boolean result = contents.removeElement(title);	
   if (result == false) {	
      throw new BookException(title + "not in cart.");	
   }	
}	
	
public Vector getContents() {	
   return contents;	
}
 

The signature of a business method must conform to these rules:

The throws clause may include exceptions that you define for your application. The removeBook method, for example, throws the BookException if the book is not in the cart.

To indicate a system-level problem, such as the inability to connect to a database, a business method should throw the javax.ejb.EJBException. When a business method throws an EJBException, the container wraps it in a RemoteException, which is caught by the client. The container will not wrap application exceptions such as BookException. Because EJBException is a subclass of RuntimeException, you do not need to include it in the throws clause of the business method.

Home Interface

A home interface extends the javax.ejb.EJBHome interface. For a session bean, the purpose of the home interface is to define the create methods that a remote client may invoke. The CartClient program, for example, invokes this create method:

Cart shoppingCart = home.create("Duke DeEarl", "123");
 

Every create method in the home interface corresponds to an ejbCreate method in the bean class. The signatures of the ejbCreate methods in the CartBean class follow:

public void ejbCreate(String person) throws CreateException   	
. . . 	
public void ejbCreate(String person, String id) 	
   throws CreateException 
 

Compare the ejbCreate signatures with those of the create methods in the CartHome interface:

import java.io.Serializable;	
import java.rmi.RemoteException;	
import javax.ejb.CreateException;	
import javax.ejb.EJBHome;	
	
public interface CartHome extends EJBHome {	
    Cart create(String person) throws 	
               RemoteException, CreateException;	
    Cart create(String person, String id) throws 	
               RemoteException, CreateException; 	
}
 

The signatures of the ejbCreate and create methods are similar, but differ in important ways. The rules for defining the signatures of the create methods of a home interface follow.

Remote Interface

The remote interface, which extends javax.ejb.EJBObject, defines the business methods that a remote client may invoke. Here is the source code for the Cart remote interface:

import java.util.*;	
import javax.ejb.EJBObject;	
import java.rmi.RemoteException;	
	
public interface Cart extends EJBObject {	
 	
   public void addBook(String title) throws RemoteException;	
   public void removeBook(String title) throws 	
                     BookException, RemoteException;	
   public Vector getContents() throws RemoteException;	
}
 

The method definitions in a remote interface must follow these rules:

Helper Classes

The CartEJB session bean has two helper classes: BookException and IdVerifier. The BookException is thrown by the removeBook method and the IdVerifier validates the customerId in one of the ejbCreate methods. Helper classes must reside in the EJB JAR file that contains the enterprise bean class.

Running the CartEJB Example

  1. Start the J2EE server and deploytool. For instructions, see the section Setting Up.
  2. In deploytool open the j2eetutorial/examples/ears/CartApp.ear file (FileOpen). You should see the application that is displayed in Figure 4-1.
  3. Deploy the CartApp application (ToolsDeploy). In the Introduction dialog box, make sure that you select the Return Client JAR checkbox. For detailed instructions, see Deploying the J2EE Application.
  4. Run the application.
    1. In a terminal window, go to the j2eetutorial/examples/ears directory.
    2. Set the APPCPATH environment variable to CartAppClient.jar.
    3. Type the following command:
         runclient -client CartApp.ear -name CartClient -textauth
       
      
    4. At the login prompts, enter guest for the user name and guest123 for the password.

Figure 4-1 General Tabbed Pane of the CartApp Application

Home
TOC
Index
PREV TOP NEXT Search
Feedback