Download The CartBean Example Application

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
The CartBean Example Application
The CartBean session 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 construct the CartBean
example, you need to create the following components:



CartRemoteInterface project
Cart EJB module project
CartClient web application
The Cart EJB module contains the session bean and the interfaces. When creating the session
bean, the IDE creates the following components:


Session bean class (CartBean)
Remote business interface (CartRemote)
All session beans require a session bean class. All enterprise beans that permit remote access must
have a home and a remote interface.
To meet the needs of a specific application, an enterprise bean may also need some helper classes.
The CartBean session bean uses two helper classes (BookException and IdVerifier) which are
discussed in the section Helper Classes.
Creating the CartRemoteInterface Project
In the IDE, you first need to create a project for storing the shared library between client
application and the session bean project.
1. Choose File
New Project (Ctrl-Shift-N).
2. In the New Project wizard, choose the Java category, select Java Library class in the
Projects pane and click Next.
3. Type CartRemoteInterface as the Project Name, specify a Project Location and click Finish.
The CartRemoteInterface appears in the Projects window of the IDE.
Creating the Cart EJB Project
In the IDE, you first need to create a project for the EJB module for the session bean.
4. Choose File
New Project (Ctrl-Shift-N).
5. In the New Project wizard, choose the Enterprise template category, select EJB Module in
the Projects pane and click Next.
6. Type Cart as the Project Name, specify a Project Location and click Finish.
The Cart module appears in the Projects window of the IDE. The next step is to add a session bean
to the module.
Creating the Session Bean
The session bean class for this example is called CartBean. Like any stateful session bean, the
CartBean class must meet these requirements:

The class is annotated @Stateful.

The class implements the business methods defined in the business interface.
Stateful session beans also may:



Implement the business interface, a plain Java interface. It is good practice to implement
the bean's business interface.
Implement any optional life cycle callback methods, annotated @PostConstruct,
@PreDestroy, @PostActivate, and @PrePassivate.
Implement any optional business methods annotated @Remove.
When you create the session bean in the IDE, the session bean interfaces are generated
automatically.
1. Right-click the Cart node in the Projects window and choose New
Session Bean.
2. Type Cart as the EJB Name, cart as the Package name, and select Stateful and Remote as
the session and select CartRemoteInterface project Then click Finish.
The IDE creates the Cart session bean under the Enterprise Beans node and opens the CartBean
class in the Source Editor. You can see that the CartBean class automatically implements the
remote and local interfaces.
The following code is the Remote Interface generated from the session Bean development.
import java.util.Vector;
import javax.ejb.Remote;
@Remote
public interface CartRemote {
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 Vector getContents();
public void remove();
}
You now need to add some private fields to the class declaration. Add the following to the class:
private String customerName;
private String customerId;
private Vector contents;
When you add the private Vector contents field, the IDE will indicate an error because you have not
yet imported the java.util.vector library. To add the necessary import statements, place the
insertion point anywhere in the class and press Alt-Shift-F to generate the following import
statements:
import java.util.Vector;
You can now start adding the create methods and business methods to the class, but for this
example you should first create the two helper classes used by the application.
Helper Classes
The CartBean session bean has two helper classes: BookException and IdVerifier. The
BookException is thrown by the removeBook and initialize methods. This class must be created in
the project CartRemoteInterface.
The IdVerifier validates the customerId in one of the ejbCreate methods.
Helper classes like IdVerifier must reside in the EJB JAR file that contains the enterprise bean class.
You will use the IDE's Java Exception wizard to create the BookException class, then you will create
a new Java class and add the code for the IdVerifier helper class
1. Right-click the CartRemoteInterface project and choose New
Java Exception.
2. Type BookException as the Class Name and exception as the Package name, ensuring that
Source Packages is selected as the Location, and click Finish.
The IDE generates the BookException class and opens the class in the Source Editor. The class has
the following code:
package exception;
public class BookException extends java.lang.Exception{
public BookException() {
}
}
public BookException(String msg) {
super(msg);
}
Now you create the second helper class called IdVerifier.
1. Right-click the Cart Project and choose New
Java Class.
2. Type IdVerifier as the Class Name and util as the Package name, ensuring that Source
Packages is selected as the Location, and click Finish.
3. In the Source Editor, add the following method to the method in the IdVerifier class:
public boolean validate(String id) {
boolean result = true;
}
for(int i = 0; i < id.length(); i++) {
if(Character.isDigit(id.charAt(i)) == false)
result = false;
}
return result;
Now that you have created the helper classes, you can add business methods to the CartBean
class. When you add the methods, the IDE adds the appropriate code to the interfaces.
Business Methods for Initializing the CartBean
You will now add two business methods to the CartBean class.
1. In the Source Editor, right-click in the body of the CartBean class and select EJB Methods
Add Business Method from the contextual menu.
2. Type initialize in the Name field, ensure that the Remote box is selected so that the method
is called in the remote interfaces and click Add in the parameter tab.
3. For the new parameter, select java.lang.String for the Type, type person in the Name field,
and then click OK to close each dialog box.
4. The IDE adds the method to the CartBean class and to the two interfaces.
5. Now add the following code to the initialize method:
if (person == null) {
throw new BookException(
"Null person not allowed.");
} else {
customerName = person;
}
customerId = "0";
contents = new Vector();
6. You will now add a second initializes method to the CartBean class. Follow steps 1-5 above
for generating a create method, this time adding the following two parameters, and in this
order:
o java.lang.String person
o java.lang.String id
7. Add the following code to the method you created in step 6:
if (person == null) {
throw new BookException(
"Null person not allowed.");
} else {
customerName = person;
}
customerId = "0";
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id;
} else {
throw new BookException("Invalid id: "+ id);
}
contents = new Vector();
Business Methods for managing the content of the CartBean
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 ejbCreate method. From
the client's perspective, the business methods appear to run locally, but they actually run remotely
in the session bean. The business methods that a client can invoke are declared in the business
interface. 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 signature of a business method must conform to these rules:


The method name must not conflict with one defined by the EJB architecture. The access
control modifier must be public.
The modifier must not be static or final.
When you add business methods in the IDE, you can use the Add Business Method contextual
menu to generate the methods. When you do this, the IDE adds the appropriate code to the
interfaces. In this example, the business methods are added to the CartBean class and the
CartRemoteBusiness interface.
1. In the Source Editor, right-click in the body of the CartBean class and select EJB Methods
Add Business Method from the contextual menu to open the Add Business Method dialog
box.
2. Enter addBook in the Name field, select void as the Return type, and ensure that the
Remote box is selected so that the method is called in the remote interfaces. Add a
parameter and select java.lang.String for the Type, enter title in the Name field, and click
OK in each dialog box to generate the method.
3. In the Source Editor, edit the addBook business method in the CartBean class so that the
method looks like this:
public void addBook(java.lang.String title) {
contents.add(title);
}
Now follow the steps above to create the removeBook and getContents business methods with the
following code:
public void removeBook(java.lang.String title) throws
BookException {
boolean result = contents.remove(title);
if (result == false) {
throw new BookException(title + "not in cart.");
}
}
public Vector getContents() {
return contents;
}
The throws clause can 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 add the exception
in the IDE using the Add Business Method dialog box, click Add in the Exceptions tab and type
BookException.
When creating the getContents business method in the IDE, you can type Vector in the Return field
in the Add Business Method dialog box.
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.
The Remove Method
In CartBean, the remove method allows to remove the bean from the container :
public void remove() {
contents = null;
}
Now follow the steps to add a business method to create the remove business method with the
above code.
Managing Your Import Statements
After you have added your create methods and business methods, you need to fix your import
statements. Import statements can be added manually, or the IDE can check and fix any import
statements in the class. Place the insertion point anywhere in the body of the class in the Source
Editor and press Alt-Shift-F to generate the necessary import statements. The IDE removes any
unused import statements and adds any missing important statements.
Your import statements for the CartBean class should contain the following:
import
import
import
import
exception.BookException;
java.util.Vector;
java.util.Enumeration;
util.IdVerifier;
package cart;
import exception.BookException;
import javax.ejb.Stateful;
import java.util.Vector;
import util.IdVerifier;
import javax.ejb.Remove;
@Stateful
public class CartBean implements CartRemote, CartLocal {
private String customerName;
private String customerId;
private Vector contents;
/** Creates a new instance of CartBean */
public CartBean() {}
public void addBook(String title) {
contents.add(title); }
public Vector getContents() {
return contents; }
public void removeBook(String title) throws BookException {
boolean result = contents.remove(title);
if (result == false) {
throw new BookException(title + "not in cart."); }}
public void initialize(String person) throws BookException {
if (person == null) { throw new BookException("Null person not allowed.");
} else { customerName = person;}
customerId = "0";
contents = new Vector(); }
public void initialize(String person, String id) throws BookException {
if (person == null) {throw new BookException( "Null person not allowed.");
} else {customerName = person;}
customerId = "0";
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) { customerId = id;
} else {throw new BookException("Invalid id: "+ id);}
contents = new Vector();
}
}
public void remove() {
contents=null;
}
Building and Deploying the Application
Now that you have finished creating the Cart EJB module, the next step is to build and deploy the
application. You then run the client application to start the session bean. The source files for the
example are available in the cart directory.
1. In the Projects window, right-click the Cart node and select Build Project from the
contextual menu.
2. Look at the Output window to ensure the application was built successfully.
3. In the Projects window, right-click the Cart node and select Deploy Project from the
contextual menu.
The deployed application is visible in the services window of the IDE. To see the deployed
application, expand the EJB Modules node in the Applications node of the server instance. You can
undeploy and disable the application in the services window.
The CartClient Application
Now that you have created the session bean, you are ready to run the client application.
Creating the CartClient Web Application
You can create the J2EE application named CartClient in the IDE.
1. Choose File
New Project (Ctrl-Shift-N) from the main menu.
2. Choose Web Applications in the Projects pane and click Next.
3. Enter WebCartClient as the Project Name, specify a Location for the project and click Finish
to create the project.
4. Right-click the WebCartClient node and choose Properties from the contextual menu.
Creating the Servlet called CartClientServlet
5. Create the servlet CartClientServlet.
6. Use the contextual menu to explain which EJB you call.
7. Add the following text :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CartClientServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet CartClientServlet at " + request.getContextPath () + "</h1>");
try {
cartBean.initialize("Duke d'Url", "123");
cartBean.addBook("Infinite Jest");
cartBean.addBook("Bel Canto");
cartBean.addBook("Kafka on the Shore");
Vector bookList = cartBean.getContents();
Enumeration enumer = bookList.elements();
while (enumer.hasMoreElements()) {
String title = (String) enumer.nextElement();
out.println("Retrieving book title from cart: " + title);
out.println ("<br>");
}
out.println("Removing \"Gravity's Rainbow\" from cart.");
out.println ("<br>");
cartBean.removeBook("Gravity's Rainbow");
cartBean.remove();
} catch (BookException ex) {
out.println("Caught a BookException: " + ex.getMessage());
out.println ("<br>");
} catch (Exception ex) {
out.println("Caught an unexpected exception!");
out.println ("<br>");
ex.printStackTrace();
}
}
out.println("</body>");
out.println("</html>");
out.close();
Running the CartClient Application
Right-click the WebCartClient node and select Run Project from the contextual menu. Lines similar
to the following are displayed in the Output window of the IDE:
running application client container.
[exec] Retrieving book title from cart: Infinite Jest
[exec] Retrieving book title from cart: Bel Canto
[exec] Retrieving book title from cart: Kafka on the Shore
[exec] Removing "Gravity's Rainbow" from cart.
[exec] Caught a BookException: "Gravity's Rainbow" not in cart.
[exec] Result: 1