The cart Example
The
cartsession bean represents a shopping cart in an online bookstore. The bean's client can add a book to the cart, remove a book, or retrieve the cart's contents. To assemblecart, you need the following code:All session beans require a session bean class. All enterprise beans that permit remote access must have a remote business interface. To meet the needs of a specific application, an enterprise bean may also need some helper classes. The
CartBeansession bean uses two helper classes (BookExceptionandIdVerifier) which are discussed in the section Helper Classes.The source code for this example is in the
<INSTALL>/javaeetutorial5/examples/ejb/cart/directory.The Business Interface
The
Cartbusiness interface is a plain Java interface that defines all the business methods implemented in the bean class. If the bean class implements a single interface, that interface is assumed to the business interface. The business interface is a local interface unless it is annotated with thejavax.ejb.Remoteannotation; thejavax.ejb.Localannotation is optional in this case.The bean class may implement more than one interface. If the bean class implements more than one interface, the bean class's business interfaces must be explicitly annotated either
@Localor@Remote. However, the following interfaces are excluded when determining if the bean class implements more than one interface:The source code for the Cart business interface follows:
package com.sun.tutorial.javaee.ejb; import java.util.List; import javax.ejb.Remote; @Remote public interface Cart { public void initialize(String person) throws BookException; public void initialize(String person, String id) throws BookException; public void addBook(String title); public void removeBook(String title) throws BookException; public List<String> getContents(); public void remove(); }Session Bean Class
The session bean class for this example is called
CartBean. Like any stateful session bean, theCartBeanclass must meet these requirements:Stateful session beans also may:
The source code for the
CartBeanclass follows.package com.sun.tutorial.javaee.ejb; import java.util.ArrayList; import java.util.List; import javax.ejb.Remove; import javax.ejb.Stateful; @Stateful public class CartBean implements Cart { String customerName; String customerId; List<String> contents; public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new ArrayList<String>(); } public void initialize(String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); } contents = new ArrayList<String>(); } public void addBook(String title) { contents.add(title); } public void removeBook(String title) throws BookException { boolean result = contents.remove(title); if (result == false) { throw new BookException(title + " not in cart."); } } public List<String> getContents() { return contents; } @Remove public void remove() { contents = null; } }Lifecycle Callback Methods
Methods in the bean class may be declared as a lifecycle call back method by annotating the method with the following annotations:
Lifecycle callback methods must be public, return
void, and have no parameters.
@PostConstructmethods are invoked by the container on newly constructed bean instances after all dependency injection has completed and before the first business method is invoked on the enterprise bean.
@PreDestroymethods are invoked after any method annotated@Removehas completed, and before the container removes the enterprise bean instance.
@PreActivatemethods are invoked by the container before the container passivates the enterprise bean, meaning the container temporarily removes the bean from the environment and saves it to secondary storage.
@PostActivatemethods are invoked by the container after the container moves the bean from secondary storage to active status.Business Methods
The primary purpose of a session bean is to run business tasks for the client. The client invokes business methods on the object reference it gets from dependency injection or JNDI lookup. 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
CartClientprogram invokes the business methods:cart.create("Duke DeEarl", "123"); ... cart.addBook("Bel Canto"); ... List<String> bookList = cart.getContents(); ... cart.removeBook("Gravity's Rainbow");The
CartBeanclass implements the business methods in the following code:public void addBook(String title) { contents.addElement(title); } public void removeBook(String title) throws BookException { boolean result = contents.remove(title); if (result == false) { throw new BookException(title + "not in cart."); } } public List<String> getContents() { return contents; }The signature of a business method must conform to these rules:
- The method name must not begin with
ejbto avoid conflicts with callback methods defined by the EJB architecture. For example, you cannot call a business methodejbCreateorejbActivate.- The access control modifier must be
public.- If the bean allows remote access via a remote business interface, the arguments and return types must be legal types for the Java RMI API.
- If the bean is a web service endpoint, the arguments and return types for the methods annotated
@WebMethodmust be legal types for JAX-WS.- The modifier must not be
staticorfinal.The
throwsclause can include exceptions that you define for your application. TheremoveBookmethod, for example, throws theBookExceptionif 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. The container will not wrap application exceptions such asBookException. BecauseEJBExceptionis a subclass ofRuntimeException, you do not need to include it in thethrowsclause of the business method.The Remove Method
Business methods annotated with
javax.ejb.Removein the stateful session bean class can be invoked by enterprise bean clients to remove the bean instance. The container will remove the enterprise bean after a@Removemethod completes, either normally or abnormally.In
CartBean, theremovemethod is a@Removemethod:Helper Classes
The
CartBeansession bean has two helper classes:BookExceptionandIdVerifier. TheBookExceptionis thrown by theremoveBookmethod, and theIdVerifiervalidates thecustomerIdin one of thecreatemethods. Helper classes may reside in the EJB JAR file that contains the enterprise bean class, or in an EAR that contains the EJB JAR.Building and Packaging the CartBean Example
Now you are ready to compile the remote interface (
Cart.java), the home interface (CartHome.java), the enterprise bean class (CartBean.java), the client class (CartClient.java), and the helper classes (BookException.javaandIdVerifier.java).Deploying the Enterprise Application
Now that the Java EE application contains the components, it is ready for deployment. To deploy
cart.ear, run the deploy task.
cart.earwill be deployed to the Application Server.Running the Application Client
When you run the client, the application client container injects any component references declared in the application client class, in this case the reference to the
Cartenterprise bean. To run the application client, perform the following steps.
- In a terminal window, go to this directory:
<INSTALL>/javaeetutorial5/examples/ejb/cart/- Type the following command:
ant runThis task will retrieve the application client JAR,
cartClient.jarand run the application client.cartClient.jarcontains the application client class, the helper classBookException, and theCartbusiness interface.This is the equivalent of running:
appclient -client cartClient.jar- In the terminal window, the client displays these lines:
...The all Task
As a convenience, the
alltask will build, package, deploy, and run the application. To do this, enter the following command:Undeploying cart
To undeploy
cart.ear, enter the following command: