Line 51 invokes OrderHome method findByPrimaryKey to obtain a remote reference to the Order with the given orderID.. Method getProductModel returns a ProductModel object containing data
Trang 1LoginServlet uses the Customer EJB to validate the userID and password that the customer entered Lines 39–44 obtain a reference to the CustomerHome interface Lines 47–48 invoke CustomerHome method findByLogin, which returns a remote reference to the Customer with the userID and password that the user provided Once the Customer is found, lines 59–69 build a simple XML document that indicates
the customer has successfully logged into the store
Lines 74–82 catch a NamingException if the Customer EJB cannot be found in the JNDI directory If no Customer is found that matches the userID and password the user entered, lines 85–93 catch a FinderException Each catch block builds an
XML error message for the client to display Lines 96–98 present the content to the client
Registered customers may want to see information about orders they have placed in the
past ViewOrderHistoryServlet (Fig 18.19) allows customers to see orders they
have placed, along with the dates the orders were taken, the total costs of the orders andwhether or not the orders were shipped from the warehouse
Fig 18.18 LoginServlet for authenticating registered Customers (part 4 of
4).(Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 227 // respond to HTTP get requests
28 public void doGet( HttpServletRequest request,
34 HttpSession session = request.getSession();
35 String userID = ( String )
Fig 18.19 ViewOrderHistoryServlet for viewing customer’s previously
placed Orders (part 1 of 4) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 352 customerHome.findByUserID( userID );
54 // create orderHistory element
55 Element rootNode = ( Element ) document.appendChild(
62 // loop through Order history and add XML elements
63 // to XML document for each Order
73 // handle exception when Customer has no Order history
74 catch ( NoOrderHistoryException historyException ) {
81 // handle exception when looking up Customer EJB
82 catch ( NamingException namingException ) {
83 namingException.printStackTrace();
85 String error = "The Customer EJB was not found in " +
86 "the JNDI directory." ;
92 // handle exception when Customer is not found
93 catch ( FinderException finderException ) {
94 finderException.printStackTrace();
96 String error = "The Customer with userID " + userID +
97 " was not found." ;
Fig 18.19 ViewOrderHistoryServlet for viewing customer’s previously
placed Orders (part 2 of 4) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 4103 // ensure content is written to client
Fig 18.19 ViewOrderHistoryServlet for viewing customer’s previously
placed Orders (part 3 of 4) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 5Customer EJB method getOrderHistory returns a Collection of the tomer’s previous orders Lines 51–52 obtain the Customer EJB for the Customer, who must be logged into the bookstore Lines 59–60 retrieve an Iterator for the customer’s
cus-order history Lines 64–70 loop through the cus-order history and build the XML document topresent to the client
If the customer has not placed any orders in our on-line store, method History throws a NoOrderHistoryException Lines 74–79 catch this exception and build an error message to display to the customer If the CustomerHome interface could not be found or the Customer could not be found in the database, a NamingEx- ception or FinderException is thrown, respectively Lines 82–101 catch each of these exceptions and construct an error message, using method buildErrorMessage Line 105 presents the content to the client, using method writeXML.
ViewOrderServlet (Fig 18.20) displays the details of an order let forwards clients to ViewOrderServlet when a customer places an order ViewOrderHistoryServlet forwards clients to ViewOrderServlet to present
CheckoutServ-the details of an order that has already been placed
Fig 18.19 ViewOrderHistoryServlet for viewing customer’s previously
placed Orders (part 4 of 4) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 6Lines 39–44 obtain a reference to interface OrderHome Lines 47–48 retrieve the orderID parameter from the request object Line 51 invokes OrderHome method findByPrimaryKey to obtain a remote reference to the Order with the given orderID Lines 54–58 get the OrderModel for the Order and append its XML repre-
sentation to the XML document
Lines 63–71 catch a NamingException, which is thrown from method lookup
if the Order EJB cannot be found in the JNDI directory Lines 74–82 catch a Exception, which is thrown by method findByPrimaryKey if an Order with the given orderID is not found Line 86 presents the XML document to the client, using method writeXML.
25 // respond to HTTP get requests
26 public void doGet( HttpServletRequest request,
27 HttpServletResponse response )
28 throws ServletException, IOException
30 Document document = getDocumentBuilder().newDocument();
31 Integer orderID = null;
38 // look up Order EJB
Fig 18.20 ViewOrderServlet for viewing details of an order (part 1 of 3) (Images
courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 746 // get orderID from request object
47 orderID = new Integer(
48 request.getParameter( "orderID" ) );
50 // find Order with given orderID
51 Order order = orderHome.findByPrimaryKey( orderID );
53 // get Order details as an OrderModel
54 OrderModel orderModel = order.getOrderModel();
62 // handle exception when looking up Order EJB
63 catch ( NamingException namingException ) {
64 namingException.printStackTrace();
66 String error = "The Order EJB was not found in " +
67 "the JNDI directory." ;
73 // handle exception when Order is not found
74 catch ( FinderException finderException ) {
75 finderException.printStackTrace();
77 String error = "An Order with orderID " + orderID +
78 " was not found." ;
Fig 18.20 ViewOrderServlet for viewing details of an order (part 2 of 3) (Images
courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 818.5.5 GetPasswordHintServlet
Registered Customers occasionally forget their passwords Servlet (Fig 18.21) provides hints to help Customers remember their passwords The
GetPasswordHint-customer supplies the password hint as part of the registration process
Fig 18.20 ViewOrderServlet for viewing details of an order (part 3 of 3) (Images
courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 9The hint is stored with other customer registration information in the Customer EJB Lines 38–47 look up the CustomerHome interface and retrieve the Customer EJB remote reference Customer EJB method getPasswordHint (line 55) returns the hint
the user entered when registering on the site Line 58 adds the hint to the XML document
In this chapter, we presented the controller and presentation logic for the Deitel store This controller logic provides an HTTP interface to the business logic objects wepresent in Chapters 18 and 19 Java servlets provide a robust and flexible controller logicimplementation XSLT presentation logic allows the Deitel Bookstore application to sup-port many different client types without a need for changes in controller logic implementa-tions In Chapters 19 and 20, we present the business logic for the Deitel Bookstore, usingEnterprise JavaBeans
25 // respond to HTTP get requests
26 public void doGet( HttpServletRequest request,
27 HttpServletResponse response )
28 throws ServletException, IOException
30 Document document = getDocumentBuilder().newDocument();
31 String userID = request.getParameter( "userID" );
Fig 18.21 GetPasswordHintServlet for viewing a Customer’s password hint
(part 1 of 3) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 1062 // handle exception when looking up Customer EJB
63 catch ( NamingException namingException ) {
64 namingException.printStackTrace();
66 String error = "The Customer EJB was not found in " +
67 "the JNDI directory." ;
73 // handle exception when Customer is not found
74 catch ( FinderException finderException ) {
Fig 18.21 GetPasswordHintServlet for viewing a Customer’s password hint
(part 2 of 3) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 11SELF-REVIEW EXERCISES
18.1 Which part of the MVC architecture do the servlets in the Deitel Bookstore implement? Whichpart of the MVC architecture do the XSL transformations implement?
Fig 18.21 GetPasswordHintServlet for viewing a Customer’s password hint
(part 3 of 3) (Images courtesy Pixo, Inc or © 2001 Nokia Mobile Phones.)
Trang 1218.2 Write a code snippet for looking up the ShoppingCart EJB in the JNDI directory and ating a new instance using interface ShoppingCartHome Be sure to catch any exceptions thrown
cre-when looking up the EJB or creating a new instance
18.3 How does ViewOrderServlet (Fig 18.20) locate the Order that the user requested to
view?
18.4 What common functionality does class XMLServlet (Fig 18.1) provide for the servlets in the Deitel Bookstore? Describe the purposes of the main methods of class XMLServlet.
18.5 How does class XMLServlet determine the name of the XSLT stylesheet to use when
transforming content generated by the servlet? What benefit does this strategy provide?
18.6 How does class XMLServlet determine the particular XSLT stylesheet to use when
trans-forming content generated by the servlet for a particular type of client? What benefit does this strategyprovide?
ANSWERS TO SELF-REVIEW EXERCISES
18.1 The servlets implement the controller in the MVC architecture, because they handle all user quests and process user input The XSL transformations implement the view in the MVC design pat-tern because they produce presentations of application data
re-18.2 The following code snippet looks up the ShoppingCart EJB in the JNDI directory and creates a new instance using interface ShoppingCartHome:
try {
InitialContext context = new InitialContext;
Object object = context.lookup(
"java:comp/env/ejb/ShoppingCart" );
ShoppingCartHome shoppingCartHome =
( ShoppingCartHome ) PortableRemoteObject.narrow( object, ShoppingCartHome.class );
ShoppingCart shoppingCart = shoppingCartHome.create(); }
catch ( NamingException namingException ) {
to transform the XML content generated by each servlet using client-specific XSL transformations
Trang 1318.5 Class XMLServlet has property XSLFileName that specifies the name of the XSL file to use when transforming the servlet’s content Class XMLServlet’s init method sets the XSL- FileName property to the value specified in the XSL_FILE servlet initialization parameter Deter-
mining the file name from an initialization parameter enables the deployer to specify the file namewhen deploying the application The file name can be changed later without the need to recompile theservlet
18.6 Class XMLServlet uses a ClientModel to determine which directory contains the XSL transformation for XML content generated by the servlet Class XMLServlet creates a list of Cli- entModel s from an XML configuration file when the servlet is first initialized Each ClientMod-
el specifies a User-Agent header that uniquely identifies the client, the Content-Type for
sending data to the client and the directory in which the XSL transformations can be found for erating content specific to the client This enables the developer to add support for new client typeswithout modifying any servlet code The developer simply provides a set of XSL transformations for
gen-the new client type and includes information about gen-the new client type in clients.xml.
Trang 14• To understand the EJB data model for the Deitel
Bookstore case study.
• To understand the business logic used in the Deitel
Bookstore case study.
• To understand performance issues involved in
transmitting objects over RMI-IIOP.
• To understand the benefits of EJBs that use
container-managed persistence for database storage.
• To understand the usage of primary-key classes that
represent complex primary keys.
Drive thy business, or it will drive thee.
Benjamin Franklin
Everybody’s business is nobody’s business, and nobody’s
business is my business.
Clara Barton
Trang 1519.1 Introduction
In this chapter, we present the EJB business logic for the shopping-cart e-commerce model,and entity EJBs that provide an object-based interface to the store’s product catalog Afterreading this chapter, you will understand the use of EJBs in an e-commerce applicationcontext, as well as more advanced EJB topics, such as custom primary-key classes andmany-to-many relationships
Trang 16ISBN GetProductServlet must then use methods in the Product remote interface
to retrieve information about the Product Each method call on the Product remote
in-terface incurs network traffic, because communication with the EJB is performed overRMI-IIOP (discussed in Chapter 27) If separate method calls were required to retrieve the
Product’s title, author, price and other properties, the network overhead would
severely limit the performance and scalability of the application
The entity EJBs in the Deitel Bookstore case study alleviate this network congestion
by using models to transmit EJB data A model is a Serializable class that contains
all the data for a given EJB These classes are called models because each model class
implements a piece of the model in the MVC architecture Each entity EJB provides a get
method that returns its model representation For example, the Product EJB has method getProductModel , which returns a ProductModel containing the ISBN, author, price and other properties of a Product Many of the entity EJBs also provide create
methods that accept models as arguments These create methods create new EJB instances
and set the data in the EJB, using property values provided in the model
Performance Tip 19.1
Aggregating entity EJB data into a model class and returning instances of this model class from EJB business methods can improve EJB performance by reducing the network traffic associated with multiple method calls over RMI-IIOP 19.1
Figure 19.1 shows a sample communication between servlet GetProductServlet and the Product EJB To get the details of a given Product, GetProductServlet invokes Product method getProductModel Method getProductModel returns
a ProductModel object containing data for a given Product and serializes the ductModel over RMI-IIOP GetProductServlet retrieves the ProductModel’s
Pro-property values to build the output for the user
19.3 ShoppingCart Implementation
Stateful session EJB ShoppingCart implements business logic for managing each tomer’s shopping cart The ShoppingCart EJB consists of a remote interface, an EJB implementation and a home interface We implement ShoppingCart as a stateful ses- sion EJB so each ShoppingCart instance will persist throughout a customer’s shopping
Cus-session Just as customers of brick-and-mortar stores use shopping carts to gather products,
customers of our on-line store use ShoppingCart EJBs to gather products while they
browse through our store
19.3.1 ShoppingCart Remote Interface
Remote interface ShoppingCart (Fig 19.2) defines business logic methods available in the ShoppingCart EJB Each remote interface method must declare that it throws RemoteException Each method also must declare any application-specific exceptions
that may be thrown from the implementation Method getContents (line 20) returns an Collection of Products in the ShoppingCart Method addProduct (lines 23– 24) takes as a String argument the ISBN of a Product to add to the ShoppingCart Method addProduct throws ProductNotFoundException, which is an applica- tion-specific exception that indicates the Product with the given ISBN is not in the da- tabase and therefore could not be added to the ShoppingCart.
Trang 17Method removeProduct (lines 27–28) removes the Product with the given ISBN from the ShoppingCart If the Product with the given ISBN is not found in the ShoppingCart , method removeProduct throws a ProductNotFoundExcep- tion.
Method setProductQuantity (lines 32–34) updates the quantity of the Product with the given ISBN in the ShoppingCart For example, if there were one
copy of Advanced Java 2 Platform How to Program in the Customer’s
Shopping-Cart, setProductQuantity could be called with the ISBN of Advanced Java How
to Program and the integer 5 to purchase five copies of the book If the Product with the
given ISBN is not in the ShoppingCart, method setProductQuantity throws the application-specific ProductNotFoundException.
Method checkout (lines 37–38) places an Order for the Products in the tomer ’s ShoppingCart Method checkout takes as a String argument the userID of the customer placing the Order Only registered customers may place Order s Method getTotal (line 41) returns the total cost of the Products in the Cus- tomer ’s ShoppingCart.
Cus-Fig 19.1 Communication between GetProductServlet and Product
Fig 19.2 ShoppingCart remote interface for adding, removing and updating
Products, checking out and calculating the Order’s total cost
(part 1 of 2)
ProductModel GetProductServlet
getProductModel
Trang 18a Collection of OrderProductModels.
16
17 public interface ShoppingCart extends EJBObject {
18
19 // get contents of ShoppingCart
20 public Collection getContents() throws RemoteException; 21
22 // add Product with given ISBN to ShoppingCart
23 public void addProduct( String isbn )
24 throws RemoteException, ProductNotFoundException;
25
26 // remove Product with given ISBN from ShoppingCart
27 public void removeProduct( String isbn )
28 throws RemoteException, ProductNotFoundException;
29
30 // change quantity of Product in ShoppingCart with
31 // given ISBN to given quantity
32 public void setProductQuantity( String isbn, int quantity )
33 throws RemoteException, ProductNotFoundException,
34 IllegalArgumentException;
35
36 // checkout ShoppingCart (i.e., create new Order)
37 public Order checkout( String userID )
38 throws RemoteException, ProductNotFoundException;
39
40 // get total cost for Products in ShoppingCart
41 public double getTotal() throws RemoteException;
Fig 19.2 ShoppingCart remote interface for adding, removing and updating
Products, checking out and calculating the Order’s total cost
(part 2 of 2)
Trang 1920 public class ShoppingCartEJB implements SessionBean {
21 private SessionContext sessionContext;
22
23 // OrderProductModels (Products & quantities) in ShoppingCart
24 private Collection orderProductModels;
25
26 // create new ShoppingCart
29 orderProductModels = new ArrayList();
31
32 // get contents of ShoppingCart
33 public Collection getContents()
35 return orderProductModels;
37
38 // add Product with given ISBN to ShoppingCart
39 public void addProduct( String isbn )
40 throws ProductNotFoundException, EJBException
Trang 2061
62 } // end while
63
64 // if Product is not in ShoppingCart, find Product with
65 // given ISBN and add OrderProductModel to ShoppingCart
76 // find Product with given ISBN
77 Product product = productHome.findByPrimaryKey( isbn );
95 // handle exception when finding Product record
96 catch ( FinderException finderException ) {
97 finderException.printStackTrace();
99 throw new ProductNotFoundException( "The Product " +
100 "with ISBN " + isbn + " was not found." );
101 }
102
103 // handle exception when invoking Product EJB methods
104 catch ( Exception exception ) {
105 throw new EJBException( exception );
106 }
107
108 } // end method addProduct
109
110 // remove Product with given ISBN from ShoppingCart
111 public void removeProduct( String isbn )
112 throws ProductNotFoundException
Fig 19.3 ShoppingCartEJB implementation of ShoppingCart remote
interface (part 3 of 7)
Trang 21134 // throw exception if Product not found in ShoppingCart
135 throw new ProductNotFoundException( "The Product " +
136 "with ISBN " + isbn + " was not found in your " +
137 "ShoppingCart." );
138
139 } // end method removeProduct
140
141 // set quantity of Product in ShoppingCart
142 public void setProductQuantity( String isbn,
143 int productQuantity ) throws ProductNotFoundException
144 {
145 // throw IllegalArgumentException if uantity not valid
146 if ( productQuantity < 0 )
147 throw new IllegalArgumentException(
148 "Quantity cannot be less than zero." );
Trang 22175 // throw exception if Product not found in ShoppingCart
176 throw new ProductNotFoundException( "The Product " +
177 "with ISBN " + isbn + " was not found in your " +
178 "ShoppingCart." );
179
180 } // end method setProductQuantity
181
182 // checkout of store (i.e., create new Order)
183 public Order checkout( String userID )
184 throws ProductNotFoundException, EJBException
185 {
186 // throw exception if ShoppingCart is empty
187 if ( orderProductModels.isEmpty() )
188 throw new ProductNotFoundException( "There were " +
189 "no Products found in your ShoppingCart." );
190
191 // create OrderModel for Order details
192 OrderModel orderModel = new OrderModel();
193
194 // set OrderModel's date to today's Date
195 orderModel.setOrderDate( new Date() );
207 // look up Order EJB
208 Object object = context.lookup(
Trang 23217 Order order = orderHome.create( orderModel, userID );
218
219 // empty ShoppingCart for further shopping
220 orderProductModels = new ArrayList();
227 // handle exception when looking up Order EJB
228 catch ( Exception exception ) {
229 throw new EJBException( exception );
230 }
231
232 } // end method checkout
233
234 // get total cost for Products in ShoppingCart
235 public double getTotal()
265 // activate ShoppingCart EJB instance
266 public void ejbActivate() {}
267
Fig 19.3 ShoppingCartEJB implementation of ShoppingCart remote
interface (part 6 of 7)
Trang 24Method addProduct (lines 39–108) adds a Product to the ShoppingCart Lines 46–62 determine if the ShoppingCart already contains the given Product If the Product is found in the ShoppingCart, lines 56–57 increment the associated Order- ProductModel ’s quantity Otherwise, method findByPrimaryKey of interface ProductHome locates the Product with the given ISBN (line 77) Lines 84–85 create an OrderProductModel to store the Product in the ShoppingCart Line 87 adds the ProductModel to the OrderProductModel, and line 88 sets the OrderProduct- Model ’s quantity to 1 Line 91 adds the OrderProductModel to the Collection, which completes the addition of the Product to the ShoppingCart.
If method findByPrimaryKey of interface ProductHome does not find the Product with the given primary key, lines 96–101 catch a FinderException Lines 99–100 throw a ProductNotFoundException to indicate that a Product with the given ISBN could not be found.
Method removeProduct (lines 111–139) compares the ISBN of each Product in the ShoppingCart’s OrderProductModel Collection with the ISBN of the Product to be removed If the Product with the given ISBN is found, line 127 removes the associated OrderProductModel from the Collection If the Product is not found in the ShoppingCart, lines 135–137 throw a ProductNotFoundExcep- tion
Method setProductQuantity (lines 142–180) sets the quantity of an OrderProductModel in the ShoppingCart If argument productQuantity is less than 0, lines 147–148 throw an IllegalArgumentException If the pro- ductQuantity equals 0, line 152 removes the Product from the ShoppingCart Lines 158–173 compare the ISBN of each Product in the OrderProductModel Collection with the given ISBN Line 169 updates the matching OrderProduct- Model ’s quantity by invoking OrderProductModel method setQuantity If the Product with the given ISBN is not found in the ShoppingCart, lines 176–178 throw a ProductNotFoundException.
Method checkout (lines 183–232) places an Order for the Products in the ShoppingCart Each Order must have an associated Customer, so method checkout takes the Customer’s userID as an argument Lines 192–201 create an OrderModel to represent the Order’s details Each Order has an orderDate, a shipped flag and a Collection of OrderProductModels Line 195 sets the date
in the OrderModel Line 198 invokes method setOrderProductModels of class OrderModel to add the OrderProductModels list to the Order Line 201 sets the shipped flag to false, to indicate that the Order has not shipped from the warehouse.
We discuss entity EJB Order in detail in Section 19.5.
268 // passivate ShoppingCart EJB instance
269 public void ejbPassivate() {}
270
271 // remove ShoppingCart EJB instance
272 public void ejbRemove() {}
273 }
Fig 19.3 ShoppingCartEJB implementation of ShoppingCart remote
interface (part 7 of 7)
Trang 25Line 217 invokes method create of interface OrderHome to create a new Order Method create takes as arguments an OrderModel containing the details of the Order to be created and a String containing the Customer’s userID Line 220 emp- ties the ShoppingCart by creating assigning a new ArrayList to Collection ref- erence orderProductModels Line 223 returns a remote reference to the newly created Order Lines 228–230 catch any exceptions that occur.
Method getTotal (lines 235–257) iterates through the Collection of ProductModels and calculates the total cost of items in the ShoppingCart.
Order-19.3.3 ShoppingCartHome Interface
Interface ShoppingCartHome (Fig 19.4) defines a single create method (lines 15– 16) that creates new ShoppingCart EJB instances The EJB container provides the im- plementation for method create.
Figure 19.5 and Figure 19.6 show the deployment settings for stateful session EJB
ShoppingCart In addition to the settings shown here, be sure to set the Transaction Type to Required for all business methods
14 // create new ShoppingCart EJB
15 public ShoppingCart create()
16 throws RemoteException, CreateException;
Fig 19.4 ShoppingCartHome interface for creating ShoppingCart EJB
instances
ShoppingCart General Deployment Settings
Bean Type Stateful Session
Trang 2619.4 Product Implementation
Entity EJB Product uses container-managed persistence to represent a Product in the
Deitel Bookstore The EJB container implements methods that select, insert, update and lete database data The deployer must provide information about how the database table
de-should be created and the SQL queries to be used for the create, remove and finder
methods at deployment time
19.4.1 Product Remote Interface
Remote interface Product (Fig 19.7) declares method getProductModel (line 17– 18), which returns a ProductModel that contains the Product’s details
ShoppingCart EJB References
Fig 19.6 ShoppingCart EJB references
ShoppingCart General Deployment Settings
Fig 19.5 ShoppingCart general deployment settings (part 2 of 2)
Trang 2719.4.2 ProductEJB Implementation
Product remote interface implementation ProductEJB (Fig 19.8) uses managed persistence The EJB container manages the synchronization of the public data members declared on lines 18–24 with the database Method getProductModel (lines 27–43) creates a ProductModel that contains the Product’s details Line 30 creates
container-the ProductModel instance, and lines 33–39 invoke set methods to initialize container-the
Pro-ductModel’s data members
16 // get Product details as ProductModel
17 public ProductModel getProductModel()
18 throws RemoteException;
1 // ProductEJB.java
2 // Entity EJB Product represents a Product, including the
3 // ISBN, publisher, author, title, price number of pages
4 // and cover image.
14 public class ProductEJB implements EntityBean {
15 private EntityContext entityContext;
16
17 // container-managed fields
Fig 19.8 ProductEJB implementation of Product remote interface (part 1 of 3).Fig 19.7 Product remote interface for modifying details of Product EJB
instances (part 2 of 2)
Trang 2823 public int pages;
25
26 // get Product details as ProductModel
27 public ProductModel getProductModel()
29 // construct new ProductModel
30 ProductModel productModel = new ProductModel();
45 // set Product details using ProductModel
46 private void setProductModel( ProductModel productModel )
60 // create instance of Product EJB using given ProductModel
61 public String ejbCreate( ProductModel productModel )
67 // perform any necessary post-creation tasks
68 public void ejbPostCreate( ProductModel productmodel ) {} 69
Trang 29Method setProductModel (lines 46–58) sets the Product’s details, using values
in the given ProductModel Line 50 sets the value of the ISBN data member to the value
of the ISBN contained in the ProductModel argument Lines 51–56 set the values of the other ProductEJB data members Method ejbCreate (lines 61–65) accepts a Pro- ductModel argument Method ejbCreate invokes method setProductModel with the provided ProductModel to initialize the Product EJB instance (line 63).
19.4.3 ProductHome Interface
Interface ProductHome (Fig 19.9) creates new ProductEJB instances and declares
finder methods for finding existing Products Method create (lines 18–19)
corre-sponds to method ejbCreate of Fig 19.8, and provides an interface for creating a ductEJB instance Method findByPrimaryKey (lines 22–23) takes as a String argument the ISBN for a particular Product in the database Method findAllProd- ucts (lines 26–27) returns a Collection of all Products in the database Method findByTitle (lines 30–31) searches for Products whose titles contain the given searchString and returns a Collection of Product remote references The EJB
Pro-container implements each finder method, using SQL queries the deployer must provide at
82 // activate Product EJB instance
85 ISBN = ( String ) entityContext.getPrimaryKey();
87
88 // passivate Product EJB instance
91 ISBN = null;
93
94 // remove Product EJB instance
97 // store Product EJB data in database
98 public void ejbStore() {}
100 // load Product EJB data from database
101 public void ejbLoad() {}
102 }
Fig 19.8 ProductEJB implementation of Product remote interface (part 3 of 3)
Trang 3017 // create Product EJB using given ProductModel
18 public Product create( ProductModel productModel )
19 throws RemoteException, CreateException;
20
21 // find Product with given ISBN
22 public Product findByPrimaryKey( String isbn )
23 throws RemoteException, FinderException;
24
25 // find all Products
26 public Collection findAllProducts()
27 throws RemoteException, FinderException;
28
29 // find Products with given title
30 public Collection findByTitle( String title )
31 throws RemoteException, FinderException;
Fig 19.9 ProductHome interface for finding and creating Product EJB
instances
1 // ProductModel.java
2 // ProductModel represents a Product in the Deitel Bookstore,
3 // including ISBN, author, title and a picture of the cover.
Trang 3287 // set number of pages
88 public void setPages( int pageCount )
90 pages = pageCount;
92
93 // get number of pages
96 return pages;
98
99 // set URL of cover image
100 public void setImage( String productImage )
101 {
102 image = productImage;
103 }
104
105 // get URL of cover image
106 public String getImage()
107 {
108 return image;
109 }
110
111 // get XML representation of Product
112 public Element getXML( Document document )
113 {
114 // create product Element
115 Element product = document.createElement( "product" );
Fig 19.10 ProductModel class for serializing Product data (part 3 of 4)
Trang 33ProductModel also implements interface XMLGenerator (Fig 19.11), which defines a single method, getXML Method getXML of class ProductModel (lines 112–
116
117 // create ISBN Element
118 Element temp = document.createElement( "ISBN" );
119 temp.appendChild(
120 document.createTextNode( getISBN() ) );
121 product.appendChild( temp );
122
123 // create publisher Element
124 temp = document.createElement( "publisher" );
125 temp.appendChild(
126 document.createTextNode( getPublisher() ) );
127 product.appendChild( temp );
128
129 // create author Element
130 temp = document.createElement( "author" );
131 temp.appendChild(
132 document.createTextNode( getAuthor() ) );
133 product.appendChild( temp );
134
135 // create title Element
136 temp = document.createElement( "title" );
144 // create price Element
145 temp = document.createElement( "price" );
146 temp.appendChild( document.createTextNode(
147 priceFormatter.format( getPrice() ) ) );
148 product.appendChild( temp );
149
150 // create pages Element
151 temp = document.createElement( "pages" );
152 temp.appendChild( document.createTextNode(
153 String.valueOf( getPages() ) ) );
154 product.appendChild( temp );
155
156 // create image Element
157 temp = document.createElement( "image" );
Trang 34164) generates an XML Element for the data contained in the ProductModel This method uses the Document argument to create XML elements for each ProductModel data member However, method getXML does not modify the Document Line 162 returns the newly created product element
Figure 19.12 and Fig 19.13 show the deployment settings for entity EJB Product.
In addition to the settings shown here, be sure to set the Transaction Type to Required
for all business methods
1 // XMLGenerator.java
2 // XMLGenerator is an interface for classes that can generate
3 // XML Elements The XML element returned by method getXML
4 // should contain Elements for each public property.
12 // build an XML element for this Object
13 public Element getXML( Document document );
Fig 19.11 XMLGenerator interface for generating XML Elements for public
properties
Product General Deployment Settings
Bean Type Entity
Fig 19.12 Product general deployment settings
Product Entity and Deployment Settings
Trang 3519.5 Order Implementation
Entity EJB Order represents an Order placed at the Deitel Bookstore Each Order sists of a list of Products and their associated quantities, as well as the customerID of the Customer who placed the Order.
UPDATE Product SET author = ?, image = ?, pages =
?, price = ?, publisher = ?, title = ? WHERE ISBN = ?
Trang 3619.5.1 Order Remote Interface
The Order EJB remote interface (Fig 19.14) defines the business methods available in the Order EJB Method getOrderModel (line 17) returns an OrderModel containing Order details Method setShipped (lines 20–21) marks an Order as having been shipped from the warehouse Method isShipped (line 24) returns a boolean that indi- cates whether the Order has been shipped.
19.5.2 OrderEJB Implementation
Order remote interface implementation OrderEJB (Fig 19.15) declares public data members for container-manage persistence (lines 26–29) Method getOrderModel (lines 32–91) constructs an OrderModel instance that contains Order details Lines 42–
44 populate the OrderModel with the values of the Order EJB’s data members
16 // get Order details as OrderModel
17 public OrderModel getOrderModel() throws RemoteException; 18
19 // set shipped flag
20 public void setShipped( boolean flag )
21 throws RemoteException;
22
23 // get shipped flag
24 public boolean isShipped() throws RemoteException;
Fig 19.14 Order remote interface for modifying details of Order EJB instances
1 // OrderEJB.java
2 // Entity EJB Order represents an Order, including the
3 // orderID, Order date, total cost and whether the Order
Trang 377 // Java core packages
20 public class OrderEJB implements EntityBean {
21 private EntityContext entityContext;
22 private InitialContext initialContext;
24
25 // container-managed fields
30
31 // get Order details as OrderModel
32 public OrderModel getOrderModel() throws EJBException
34 // construct new OrderModel
35 OrderModel orderModel = new OrderModel();
36
37 // look up OrderProduct EJB to retrieve list
38 // of Products contained in the Order
59 Iterator iterator = orderProducts.iterator();
Fig 19.15 OrderEJB implementation of Order remote interface (part 2 of 6)
Trang 3860
61 // OrderProductModels to place in OrderModel
62 Collection orderProductModels = new ArrayList();
74 // add OrderProductModel to list of
75 // OrderProductModels in the Order
84 // handle exception working with OrderProduct EJB
85 catch ( Exception exception ) {
86 throw new EJBException( exception );
93 // set shipped flag
94 public void setShipped( boolean flag )
96 shipped = flag;
98
99 // get shipped flag
100 public boolean isShipped()
101 {
102 return shipped;
103 }
104
105 // create new Order EJB using given OrderModel and userID
106 public Integer ejbCreate( OrderModel order, String userID )
107 throws CreateException
108 {
109 // retrieve unique value for primary key of this
110 // Order using SequenceFactory EJB
111 try {
112 initialContext = new InitialContext();
Fig 19.15 OrderEJB implementation of Order remote interface (part 3 of 6)
Trang 39130 // get date, cost, shipped flag and list of
131 // OrderProduct from provided OrderModel
132 orderDate = dateFormat.format( order.getOrderDate() );
139 // create OrderProduct EJBs for each Product in
140 // Order to keep track of quantity
150 // create an OrderProduct EJB with Product's
151 // ISBN, quantity and orderID for this Order
Trang 40180 // handle exception when looking up EJBs
181 catch ( Exception exception ) {
182 throw new CreateException( exception.getMessage() );
189 // perform any necessary post-creation tasks
190 public void ejbPostCreate( OrderModel order, String id ) {} 191
206 // activate Order EJB instance
207 public void ejbActivate()
208 {
209 orderID = ( Integer ) entityContext.getPrimaryKey();
210 }
211
212 // passivate Order EJB instance
213 public void ejbPassivate()
214 {
215 orderID = null;
216 }
217
218 // remove Order EJB instanceCus
Fig 19.15 OrderEJB implementation of Order remote interface (part 5 of 6)