105
2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet Base Class 18.3 Shopping Cart Servlets 18.3.1 AddToCartServlet 18.3.2 ViewCartServlet 18.3.3 RemoveFromCartServlet 18.3.4 UpdateCartServlet 18.3.5 CheckoutServlet 18.4 Product Catalog Servlets 18.4.1 GetAllProductsServlet 18.4.2 GetProductServlet 18.4.3 ProductSearchServlet 18.5 Customer Management Servlets 18.5.1 RegisterServlet 18.5.2 LoginServlet 18.5.3 ViewOrderHistoryServlet 18.5.4 ViewOrderServlet 18.5.5 GetPasswordHintServlet

2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

Embed Size (px)

Citation preview

Page 1: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic

Outline18.1 Introduction18.2 XMLServlet Base Class18.3 Shopping Cart Servlets

18.3.1 AddToCartServlet18.3.2 ViewCartServlet18.3.3 RemoveFromCartServlet18.3.4 UpdateCartServlet18.3.5 CheckoutServlet

18.4 Product Catalog Servlets18.4.1 GetAllProductsServlet18.4.2 GetProductServlet18.4.3 ProductSearchServlet

18.5 Customer Management Servlets18.5.1 RegisterServlet18.5.2 LoginServlet18.5.3 ViewOrderHistoryServlet18.5.4 ViewOrderServlet18.5.5 GetPasswordHintServlet

Page 2: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.1 Introduction

• Controller logic– Process user requests

– Java servlets in the Deitel Bookstore implementation

• Presentation logic– Show the output from the request to the user

– XSL transformations

Page 3: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.2 XMLServlet Base Class

• XMLServlet base class– Common initialization and utility methods

– Create XML document

– XSLT transformation

Page 4: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

1 // XMLServlet.java2 // XMLServlet is a base class for servlets that generate 3 // XML documents and perform XSL transformations.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 import java.util.*;9 import java.net.URL;10 11 // Java extension packages12 import javax.servlet.*;13 import javax.servlet.http.*;14 import javax.xml.parsers.*;15 import javax.xml.transform.*;16 import javax.xml.transform.dom.*;17 import javax.xml.transform.stream.*;18 19 // third-party packages20 import org.w3c.dom.*;21 import org.xml.sax.SAXException;22 23 // Deitel packages24 import com.deitel.advjhtp1.bookstore.model.*;25 26 public class XMLServlet extends HttpServlet {27 28 // factory for creating DocumentBuilders29 private DocumentBuilderFactory builderFactory;30 31 // factory for creating Transformers32 private TransformerFactory transformerFactory;33 34 // XSL file that presents servlet's content35 private String XSLFileName;

Page 5: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 41-85

Line 49

Line 52

Line 55

Lines 58-81

Line 67

36 37 // ClientModel List for determining client type38 private List clientList;39 40 // initialize servlet41 public void init( ServletConfig config ) 42 throws ServletException43 { 44 // call superclass's init method for initialization45 super.init( config );46 47 // use InitParameter to set XSL file for transforming 48 // generated content49 setXSLFileName( config.getInitParameter( "XSL_FILE" ) );50 51 // create new DocumentBuilderFactory52 builderFactory = DocumentBuilderFactory.newInstance(); 53 54 // create new TransformerFactory55 transformerFactory = TransformerFactory.newInstance();56 57 // set URIResolver for resolving relative paths in XSLT58 transformerFactory.setURIResolver( 59 60 new URIResolver() {61 62 // resolve href as relative to ServletContext63 public Source resolve( String href, String base )64 {65 try { 66 ServletContext context = getServletContext();67 URL url = context.getResource( href );68 69 // create StreamSource to read document from URL70 return new StreamSource( url.openStream() );

Method init initializes the servlet.

Retrieves the name of the XSL transformation that will transform the servlet’s content for each client type.

Creates a DocumentBuilderFactory instance, which will be used to create DocumentBuilders for building XML documents.

Creates a TransformerFactory, which which instances of XMLServlet perform XSL transformations.

Set a URIResolver for the TransformerFactory to enable its Transformers to resolve relative URIs in XSL documents.

Resolves the relative URI by invoking ServletContext method getResource.

Page 6: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Line 84

Lines 88-107

71 } 72 73 // handle exceptions obtaining referenced document74 catch ( Exception exception ) { 75 exception.printStackTrace(); 76 77 return null;78 }79 }80 }81 ); // end call to setURIResolver 82 83 // create ClientModel ArrayList84 clientList = buildClientList();85 }86 87 // get DocumentBuilder instance for building XML documents88 public DocumentBuilder getDocumentBuilder( boolean validating ) 89 { 90 // create new DocumentBuilder91 try {92 93 // set validation mode94 builderFactory.setValidating( validating );95 96 // return new DocumentBuilder to the caller97 return builderFactory.newDocumentBuilder(); 98 }99 100 // handle exception when creating DocumentBuilder101 catch ( ParserConfigurationException parserException ) { 102 parserException.printStackTrace(); 103 104 return null;105 }

Method getDocumentBuilder creates a DocumentBuilder object for parsing and creating XML documents.

Create an ActivationDesc object for the ChatServer remote object.

Page 7: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 110-113

Lines 116-125

Lines 130-168

Lines 138-139

106 107 } // end method getDocumentBuilder108 109 // get non-validating parser110 public DocumentBuilder getDocumentBuilder()111 {112 return getDocumentBuilder( false );113 }114 115 // set XSL file name for transforming servlet's content116 public void setXSLFileName( String fileName )117 {118 XSLFileName = fileName;119 }120 121 // get XSL file name for transforming servlet's content122 public String getXSLFileName() 123 { 124 return XSLFileName;125 } 126 127 // write XML document to client using provided response 128 // Object after transforming XML document with 129 // client-specific XSLT document130 public void writeXML( HttpServletRequest request,131 HttpServletResponse response, Document document ) 132 throws IOException 133 {134 // get current session, create if not extant135 HttpSession session = request.getSession( true );136 137 // get ClientModel from session Object138 ClientModel client = ( ClientModel ) 139 session.getAttribute( "clientModel" );140

Invokes method getDocumentBuilder with a false argument to create a non-validating XML parser.

Set and get methods for the XSLFileName property of class XMLServlet.

Determines which type of client is accessing the servlet and invokes method transform to perform an XSL transformation.

Obtain a ClientModel from the HttpSession.

Page 8: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Line 144

Line 145

Line 146

Line 150

Line 156

Line 159-160

Line 163

141 // if client is null, get new ClientModel for this142 // User-Agent and store in session143 if ( client == null ) {144 String userAgent = request.getHeader( "User-Agent" ); 145 client = getClientModel( userAgent );146 session.setAttribute( "clientModel", client ); 147 }148 149 // set appropriate Content-Type for client150 response.setContentType( client.getContentType() );151 152 // get PrintWriter for writing data to client153 PrintWriter output = response.getWriter();154 155 // build file name for XSLT document156 String xslFile = client.getXSLPath() + getXSLFileName();157 158 // open InputStream for XSL document 159 InputStream xslStream = 160 getServletContext().getResourceAsStream( xslFile );161 162 // transform XML document using XSLT163 transform( document, xslStream, output );164 165 // flush and close PrintWriter166 output.close();167 168 } // end method writeXML169

Obtains the client’s User-Agent header.Invokes method getClientModel

to get an appropriate ClientModel for the given client type.

Places the ClientModel in the HttpSession for later use.

Obtains the content type for the client from the ClientModel and configure the HttpServletResponse object.Constructs the complete relative path for the XSL transformation.Open an InputStream for

the XSL transformation.

Invokes method transform to perform the transformation and send the result to the client.

Page 9: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 172-202

Line 179

Lines 182-183

Lines 189-190

Line 193

170 // transform XML document using provided XSLT InputStream 171 // and write resulting document to provided PrintWriter172 public void transform( Document document, 173 InputStream xslStream, PrintWriter output )174 {175 // create Transformer and apply XSL transformation176 try {177 178 // create DOMSource for source XML document179 Source xmlSource = new DOMSource( document );180 181 // create StreamSource for XSLT document182 Source xslSource = 183 new StreamSource( xslStream );184 185 // create StreamResult for transformation result186 Result result = new StreamResult( output );187 188 // create Transformer for XSL transformation189 Transformer transformer = 190 transformerFactory.newTransformer( xslSource );191 192 // transform and deliver content to client193 transformer.transform( xmlSource, result );194 195 } // end try196 197 // handle exception when transforming XML document198 catch ( TransformerException transformerException ) { 199 transformerException.printStackTrace(); 200 }201 202 } // end method transform203

Performs the given XSL transformation on the given XML document, and writes the result of the transformation to the given PrintWriter.

Creates a DOMSource for the XML document.

Create a StreamSource for the XSL document.

Create a Transformer by invoking TransformerFactory method newTransformer.Invokes Transformer method transform to perform the XSL transformation on the given Source object and writes the result to the given Result object.

Page 10: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 205-223

Line 209

Lines 212-213

Lines 216-217

Line 220

Lines 227-323

Lines 237-238

204 // build error element containing error message205 public Node buildErrorMessage( Document document,206 String message)207 {208 // create error element209 Element error = document.createElement( "error" );210 211 // create message element212 Element errorMessage = 213 document.createElement( "message" );214 215 // create message text and append to message element216 errorMessage.appendChild( 217 document.createTextNode( message ) );218 219 // append message element to error element220 error.appendChild( errorMessage );221 222 return error;223 } 224 225 // build list of ClientModel Objects for delivering226 // appropriate content to each client227 private List buildClientList()228 {229 // get validating DocumentBuilder for client XML document230 DocumentBuilder builder = getDocumentBuilder( true );231 232 // create client ArrayList233 List clientList = new ArrayList();234 235 // get name of XML document containing client 236 // information from ServletContext237 String clientXML = getServletContext().getInitParameter( 238 "CLIENT_LIST" );

Utility method for constructing XML Element that contains an error message.

Creates an error Element using the provided document.

Create a errorMessage Element that will contain the actual error message.

Create a Text node that contains the text of the error message and append this Text node to the errorMessage Element.Appends the errorMessage Element to the error Element.

Constructs a List of ClientModels by reading client information from an XML configuration file.

Retrieve the name of the configuration file from an initialization parameter in the servlet’s ServletContext.

Page 11: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 244-246

Lines 249-250

Lines 253-254

Lines 260-306

239 240 // read clients from XML document and build ClientModels241 try { 242 243 // open InputStream to XML document244 InputStream clientXMLStream = 245 getServletContext().getResourceAsStream( 246 clientXML );247 248 // parse XML document249 Document clientsDocument = 250 builder.parse( clientXMLStream );251 252 // get NodeList of client elements253 NodeList clientElements = 254 clientsDocument.getElementsByTagName( "client" );255 256 // get length of client NodeList257 int listLength = clientElements.getLength(); 258 259 // process NodeList of client Elements260 for ( int i = 0; i < listLength; i++ ) {261 262 // get next client Element263 Element client = 264 ( Element ) clientElements.item( i );265 266 // get agent Element from client Element267 Element agentElement = ( Element ) 268 client.getElementsByTagName( 269 "userAgent" ).item( 0 );270 271 // get agent Element's child text node272 Text agentText = 273 ( Text ) agentElement.getFirstChild();

Open an InputStream to the configuration file.

Parse the XML configuration file and build a Document object in memory.

Get a NodeList of client Elements from the document.

Construct a ClientModel for each client Element in the XML configuration file and add those ClientModels to the List.

Page 12: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

274 275 // get value of agent Text node276 String agent = agentText.getNodeValue();277 278 // get contentType Element279 Element typeElement = ( Element ) 280 client.getElementsByTagName( 281 "contentType" ).item( 0 );282 283 // get contentType Element's child text node284 Text typeText = 285 ( Text ) typeElement.getFirstChild(); 286 287 // get value of contentType text node288 String type = typeText.getNodeValue(); 289 290 // get XSLPath element291 Element pathElement = ( Element ) 292 client.getElementsByTagName( 293 "XSLPath" ).item( 0 );294 295 // get Text node child of XSLPath296 Text pathText = 297 ( Text ) pathElement.getFirstChild(); 298 299 // get value of XSLPath text node300 String path = pathText.getNodeValue(); 301 302 // add new ClientModel with userAgent, contentType303 // and XSLPath for this client Element304 clientList.add( 305 new ClientModel( agent, type, path ) );306 } 307 308 } // end try

Page 13: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 326-347

309 310 // handle SAXException when parsing XML document311 catch ( SAXException saxException ) {312 saxException.printStackTrace();313 }314 315 // catch IO exception when reading XML document316 catch ( IOException ioException ) {317 ioException.printStackTrace();318 }319 320 // return newly creating list of ClientModels321 return clientList;322 323 } // end method buildClientList324 325 // get ClientModel for given User-Agent HTTP header326 private ClientModel getClientModel( String header )327 {328 // get Iterator for clientList329 Iterator iterator = clientList.iterator();330 331 // find ClientModel whose userAgent property is a 332 // substring of given User-Agent HTTP header333 while ( iterator.hasNext() ) {334 ClientModel client = ( ClientModel ) iterator.next();335 336 // if this ClientModel's userAgent property is a337 // substring of the User-Agent HTTP header, return 338 // a reference to the ClientModel339 if ( header.indexOf( client.getUserAgent() ) > -1 )340 return client;341 }342

Returns a ClientModel that matches the given User-Agent header.

Page 14: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.1 XMLServlet base class for servlets in the Deitel Bookstore.

Lines 344-345

343 // return default ClientModel if no others match344 return new ClientModel( 345 "DEFAULT CLIENT", "text/html", "/XHTML/" );346 347 } // end method getClientModel348 }

Construct a generic XHTML ClientModel as a default if no other match the given User-Agent header.

Page 15: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.2 Configuration file for enabling support for various client types (clients.xml).

1 <?xml version = "1.0" encoding = "UTF-8"?>2 <!DOCTYPE clients SYSTEM 3 "http://www.deitel.com/advjhtp1/clients.dtd">4 5 <!-- Client configuration file for the Deitel Bookstore -->6 7 <clients>8 9 <!-- Microsoft Internet Explorer version 5 client -->10 <client name = "Microsoft Internet Explorer 5">11 <userAgent>Mozilla/4.0 (compatible; MSIE 5</userAgent>12 <contentType>text/html</contentType>13 <XSLPath>/XSLT/XHTML/</XSLPath>14 </client>15 16 <!-- Microsoft Internet Explorer version 6 client -->17 <client name = "Microsoft Internet Explorer 6">18 <userAgent>Mozilla/4.0 (compatible; MSIE 6</userAgent>19 <contentType>text/html</contentType>20 <XSLPath>/XSLT/XHTML/</XSLPath>21 </client>22 23 <!-- Netscape version 4.7x client -->24 <client name = "Netscape 4.7">25 <userAgent>Mozilla/4.7</userAgent>26 <contentType>text/html</contentType>27 <XSLPath>/XSLT/XHTML/</XSLPath>28 </client>29 30 <!-- Mozilla/Netscape version 6 client -->31 <client name = "Mozilla/Netscape 6">32 <userAgent>Gecko</userAgent>33 <contentType>text/html</contentType>34 <XSLPath>/XSLT/XHTML/</XSLPath>35 </client>

Page 16: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.2 Configuration file for enabling support for various client types (clients.xml).

36 37 <!-- Phone.com WML browser client -->38 <client name = "Openwave SDK Browser">39 <userAgent>UP.Browser/4</userAgent>40 <contentType>text/vnd.wap.wml</contentType>41 <XSLPath>/XSLT/WML/</XSLPath>42 </client>43 44 <!-- Nokia WML browser client -->45 <client name = "Nokia WAP Toolkit Browser">46 <userAgent>Nokia-WAP</userAgent>47 <contentType>text/vnd.wap.wml</contentType>48 <XSLPath>/XSLT/WML/</XSLPath>49 </client>50 51 <!-- Pixo iMode browser client -->52 <client name = "Pixo Browser">53 <userAgent>Pixo-Browser</userAgent>54 <contentType>text/html</contentType>55 <XSLPath>/XSLT/cHTML/</XSLPath>56 </client>57 58 </clients>

Page 17: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.3 DTD for clients.xml.

1 <!-- clients.dtd -->2 <!-- DTD for specifying Bookstore client types -->3 4 <!ELEMENT clients ( client+ )>5 6 <!ELEMENT client ( userAgent, contentType, XSLPath )>7 <!ATTLIST client name CDATA #REQUIRED>8 9 <!ELEMENT userAgent ( #PCDATA )>10 <!ELEMENT contentType ( #PCDATA )>11 <!ELEMENT XSLPath ( #PCDATA )>

Page 18: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.4 ClientModel for representing supported clients.

Lines 26-35

1 // ClientModel.java2 // ClientModel is a utility class for determining the proper 3 // Content-Type and path for XSL files for each type of client 4 // supported by the Bookstore application.5 package com.deitel.advjhtp1.bookstore.model;6 7 // Java core packages8 import java.io.*;9 10 public class ClientModel implements Serializable {11 12 // ClientModel properties13 private String userAgent;14 private String contentType;15 private String XSLPath;16 17 // ClientModel constructor for initializing data members18 public ClientModel( String agent, String type, String path )19 {20 setUserAgent( agent );21 setContentType( type );22 setXSLPath( path );23 }24 25 // set UserAgent substring 26 public void setUserAgent( String agent )27 {28 userAgent = agent;29 }30 31 // get UserAgent substring32 public String getUserAgent()33 {34 return userAgent;35 }

Set and get methods for the UserAgent.

Page 19: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.4 ClientModel for representing supported clients.

Lines 38-47

Lines 50-59

36 37 // set ContentType38 public void setContentType( String type )39 {40 contentType = type;41 }42 43 // get ContentType44 public String getContentType()45 {46 return contentType;47 }48 49 // set XSL path50 public void setXSLPath( String path )51 {52 XSLPath = path;53 }54 55 // get XSL path56 public String getXSLPath()57 {58 return XSLPath;59 }60 }

Set and get methods for the ContentType.

Set and get methods for the XSLPath.

Page 20: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3 Shopping Cart Servlets

• Shopping-cart model– Browse the store

– Select items for purchase

– Place items in a virtual shopping cart

– Checkout

Page 21: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3 Shopping Cart Servlets (Cont.)

register.html

index.html GetAllProductsServlet GetProductServlet

UpdateCartServlet ViewCartServlet AddToCartServlet

RegisterServlet

LoginServlet CheckoutServlet ViewOrderServlet

Fig. 18.5 Flow of client requests and data returned in the Deitel Bookstore for XHTML clients.

Page 22: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3.1 AddToCartServlet

• AddToCartServlet– Extends XMLServlet– Adds a product to the shopping cart

Page 23: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.6 AddToCartServlet for adding products to a shopping cart.

1 // AddToCartServlet.java2 // AddToCartServlet adds a Product to the Customer's 3 // ShoppingCart.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 9 // Java extension packages10 import javax.servlet.*;11 import javax.servlet.http.*;12 import javax.naming.*;13 import javax.rmi.*;14 import javax.ejb.*;15 16 // third-party packages17 import org.w3c.dom.*;18 19 // Deitel packages20 import com.deitel.advjhtp1.bookstore.model.*;21 import com.deitel.advjhtp1.bookstore.ejb.*;22 import com.deitel.advjhtp1.bookstore.exceptions.*;23 24 public class AddToCartServlet extends XMLServlet {25 26 // respond to HTTP post requests27 public void doPost( HttpServletRequest request,28 HttpServletResponse response )29 throws ServletException, IOException30 {31 Document document = getDocumentBuilder().newDocument();32 33 // get HttpSession Object for this user34 HttpSession session = request.getSession();35

Page 24: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.6 AddToCartServlet for adding products to a shopping cart.

Lines 37-38

Line 59

Line 62

Line 66

Line 70

36 // get Customer's ShoppingCart37 ShoppingCart shoppingCart = 38 ( ShoppingCart ) session.getAttribute( "cart" );39 40 // get ISBN parameter from request Object41 String isbn = request.getParameter( "ISBN" );42 43 // get ShoppingCart and add Product to be purchased44 try { 45 InitialContext context = new InitialContext();46 47 // create ShoppingCart if Customer does not have one48 if ( shoppingCart == null ) {49 Object object = context.lookup( 50 "java:comp/env/ejb/ShoppingCart" );51 52 // cast Object reference to ShoppingCartHome53 ShoppingCartHome shoppingCartHome = 54 ( ShoppingCartHome ) 55 PortableRemoteObject.narrow(56 object, ShoppingCartHome.class );57 58 // create ShoppingCart using ShoppingCartHome59 shoppingCart = shoppingCartHome.create();60 61 // store ShoppingCart in session62 session.setAttribute( "cart", shoppingCart );63 }64 65 // add Product to Customer's ShoppingCart66 shoppingCart.addProduct( isbn );67 68 // redirect Customer to ViewCartServlet to view69 // contents of ShoppingCart70 response.sendRedirect( "ViewCart" );

Retrieve a reference to the customer’s ShoppingCart from the servlet’s HttpSession object.

Creates a new ShoppingCart using the ShoppingCart home interface.Stores shoppingCart in

the servlet’s HttpSession object for later use.

Invokes the ShoppingCart’s addProduct business method with the product’s ISBN as an argument.

Invokes method sendRedirect to redirect the client to ViewCartServlet.

Page 25: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.6 AddToCartServlet for adding products to a shopping cart.

Lines 75-86

Lines 89-99

Lines 102-110

71 72 } // end try73 74 // handle exception when looking up ShoppingCart EJB75 catch ( NamingException namingException ) { 76 namingException.printStackTrace(); 77 78 String error = "The ShoppingCart EJB was not " +79 "found in the JNDI directory.";80 81 // append error message to XML document82 document.appendChild( buildErrorMessage( 83 document, error ) );84 85 writeXML( request, response, document );86 }87 88 // handle exception when creating ShoppingCart EJB89 catch ( CreateException createException ) { 90 createException.printStackTrace(); 91 92 String error = "ShoppingCart could not be created";93 94 // append error message to XML document95 document.appendChild( buildErrorMessage( 96 document, error ) );97 98 writeXML( request, response, document );99 }100 101 // handle exception when Product is not found102 catch ( ProductNotFoundException productException ) {103 productException.printStackTrace();104

Catch a NamingException if the ShoppingCart EJB is not found in the JNDI directory.

Catch a CreateException if there is an error creating the customer’s shopping cart.

Catch a ProductNotFoundException if the given ISBN could not be found in the database.

Page 26: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.6 AddToCartServlet for adding products to a shopping cart.

Lines 85, 98, 109

105 // append error message to XML document106 document.appendChild( buildErrorMessage( 107 document, productException.getMessage() ) );108 109 writeXML( request, response, document ); 110 }111 112 } // end method doGet113 }

Invoking XMLServlet method writeXML sends the content to the client.

Page 27: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3.2 ViewCartServlet

• ViewCartServlet– Display the shopping cart’s contents

Page 28: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.7 ViewCartServlet for viewing contents of shopping cart.

Lines 34-35

1 // ViewCartServlet.java2 // ViewCartServlet presents the contents of the Customer's 3 // ShoppingCart.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages 7 import java.io.*;8 import java.util.*;9 import java.text.*;10 11 // Java extension packages12 import javax.servlet.*;13 import javax.servlet.http.*;14 import javax.rmi.*;15 16 // third-party packages17 import org.w3c.dom.*;18 19 // Deitel packages20 import com.deitel.advjhtp1.bookstore.model.*;21 import com.deitel.advjhtp1.bookstore.ejb.*;22 23 public class ViewCartServlet extends XMLServlet {24 25 // respond to HTTP get requests26 public void doGet( HttpServletRequest request,27 HttpServletResponse response )28 throws ServletException, IOException29 {30 Document document = getDocumentBuilder().newDocument();31 HttpSession session = request.getSession();32 33 // get Customer's ShoppingCart from session34 ShoppingCart shoppingCart = 35 ( ShoppingCart ) session.getAttribute( "cart" );

Retrieve customer’s ShoppingCart.

Page 29: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.7 ViewCartServlet for viewing contents of shopping cart.

Lines 41-42

Line 45

Lines 48-49

Lines 62-68

Line 67

36 37 // build XML document with contents of ShoppingCart 38 if ( shoppingCart != null ) {39 40 // create cart element in XML document41 Element root = ( Element ) document.appendChild( 42 document.createElement( "cart" ) );43 44 // get total cost of Products in ShoppingCart45 double total = shoppingCart.getTotal();46 47 // create NumberFormat for local currency48 NumberFormat priceFormatter =49 NumberFormat.getCurrencyInstance();50 51 // format total price for ShoppingCart and add it 52 // as an attribute of element cart53 root.setAttribute( "total", 54 priceFormatter.format( total ) );55 56 // get contents of ShoppingCart57 Iterator orderProducts = 58 shoppingCart.getContents().iterator();59 60 // add an element for each Product in ShoppingCart61 // to XML document62 while ( orderProducts.hasNext() ) {63 OrderProductModel orderProductModel = 64 ( OrderProductModel ) orderProducts.next();65 66 root.appendChild( 67 orderProductModel.getXML( document ) );68 }69 70 } // end if

Begin building the XML document that describes the customer’s shopping cart by creating element cart.Obtains the total price for the

items in the shopping cart.

Format the total using a NumberFormat and append the formatted total to the XML document.

Iterate through the Collection of OrderProductModels in the shopping cart.

Invokes OrderProductModel method getXML to obtain an XML element that describes the OrderProductModel.

Page 30: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.7 ViewCartServlet for viewing contents of shopping cart.

Lines 72-78

Line 81

71 72 else { 73 String error = "Your ShoppingCart is empty.";74 75 // append error message to XML document76 document.appendChild( buildErrorMessage( 77 document, error ) ); 78 }79 80 // write content to client81 writeXML( request, response, document ); 82 83 } // end method doGet84 }

Generate an error message if ShoppingCart is null.

Invokes method writeXML to transforms the XML content using XSLT and present that content to the client.

Page 31: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.8 ViewCartServlet XSL transformation for XHTML browsers (XHTML/viewCart.xsl).

Lines 6-8

Line 10

Lines 23-27

1 <?xml version = "1.0"?>2 3 <xsl:stylesheet version = "1.0"4 xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">5 6 <xsl:output method = "xml" omit-xml-declaration = "no" 7 indent = "yes" doctype-system = "DTD/xhtml1-strict.dtd"8 doctype-public = "-//W3C//DTD XHTML 1.0 Strict//EN"/>9 10 <xsl:include href = /XSLT/XHTML/error.xsl"/>11 12 <xsl:template match = "cart">13 <html xmlns = "http://www.w3.org/1999/xhtml" 14 xml:lang = "en" lang = "en">15 16 <head>17 <title>Your Online Shopping Cart</title>18 <link rel = "StyleSheet" href = "styles/default.css"/>19 </head>20 21 <body>22 23 <xsl:for-each select =24 "document( '/XSLT/XHTML/navigation.xml' )">25 26 <xsl:copy-of select = "."/>27 </xsl:for-each>28 29 <div class = "header">Your Shopping Cart:</div>30

Set the output parameters for the transformation.

Includes templates from error.xsl for transforming error message.

Load a navigation header from an external XML document.

Page 32: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.8 ViewCartServlet XSL transformation for XHTML browsers (XHTML/viewCart.xsl).

Lines 31-43

Lines 51-54

Lines 61-91

31 <table class = "cart">32 <tr>33 <th>Title</th>34 <th>Author(s)</th>35 <th>ISBN</th>36 <th>Price</th>37 <th>Quantity</th> 38 </tr>39 40 <xsl:apply-templates 41 select = "orderProduct"/>42 43 </table>44 45 <p>46 Your total: 47 <xsl:value-of select = "@total"/> 48 </p> 49 50 <p>51 <form action = "Checkout" method = "post">52 <input name = "submit" type = "submit" 53 value = "Check Out"/>54 </form>55 </p>56 57 </body>58 </html> 59 </xsl:template>60 61 <xsl:template match = "orderProduct">62 <tr>63 <td>64 <a href = "GetProduct?ISBN={product/ISBN}">65 <xsl:value-of select = "product/title"/></a>

Apply a template that populates a table with product information.

The form enables the customer to check out from the online store to place the order.

This template extracts each product’s information from the ViewCartServelt’s XML document and creates a table row.

Page 33: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.8 ViewCartServlet XSL transformation for XHTML browsers (XHTML/viewCart.xsl).

Lines 75-80

Lines 84-88

66 </td> 67 68 <td><xsl:value-of select = "product/author"/></td>69 70 <td><xsl:value-of select = "product/ISBN"/></td>71 72 <td><xsl:value-of select = "product/price"/></td>73 74 <td>75 <form action = "UpdateCart" method = "post">76 <input type = "text" size = "2" 77 name = "{product/ISBN}" 78 value = "{quantity}"/>79 <input type = "submit" value = "Update"/>80 </form>81 </td>82 83 <td align = "center">84 <form action = "RemoveFromCart" method = "post">85 <input name = "ISBN" type = "hidden" 86 value = "{product/ISBN}"/>87 <input type = "submit" value = "Remove"/>88 </form>89 </td>90 </tr>91 </xsl:template>92 </xsl:stylesheet>

This form enables the user to change the quantity of the product in the shopping cart.

This form enables the user to remove the product from the shopping cart.

Page 34: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.8 ViewCartServlet XSL transformation for XHTML browsers (XHTML/viewCart.xsl).

Program output

Page 35: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.9 ViewCartServlet XSL transformation for I-mode browsers (cHTML/viewCart.xsl).

Lines 28-29

1 <?xml version = "1.0"?>2 3 <xsl:stylesheet version = "1.0"4 xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">5 6 <xsl:output method = "html" 7 omit-xml-declaration = "yes" 8 indent = "yes" 9 doctype-system = 10 "http://www.w3.org/MarkUp/html-spec/html-spec_toc.html"11 doctype-public = "-//W3C//DTD HTML 2.0//EN"/>12 13 <xsl:include href = "/XSLT/cHTML/error.xsl"/>14 15 <xsl:template match = "cart">16 <html>17 18 <head>19 <title>Your Online Shopping Cart</title>20 </head>21 22 <body>23 <div class = "header">24 Your Shopping Cart:25 </div>26 27 <p>28 Your total: 29 <xsl:value-of select = "@total"/> 30 </p> 31 32 <p>Title</p>33 <p>Author(s)</p>34 <p>ISBN</p>35 <p>Price</p>

Display the total cost of products in the cart.

Page 36: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.9 ViewCartServlet XSL transformation for I-mode browsers (cHTML/viewCart.xsl).

Lines 38-41

Lines 44-47

Lines 64-69

36 <p>Quantity</p> 37 38 <ul>39 <xsl:apply-templates 40 select = "orderProduct"/>41 </ul>42 43 <p>44 <form method = "post" action = "Checkout">45 <input type = "submit" name = "Checkout" 46 value = "Checkout"/>47 </form>48 </p>49 50 </body>51 52 </html> 53 </xsl:template>54 55 <xsl:template match = "orderProduct">56 <li>57 <a href = "GetProduct?ISBN={product/ISBN}">58 <xsl:value-of select = "product/title"/></a>59 <br/> 60 <p><xsl:value-of select = "product/author"/></p>61 <p><xsl:value-of select = "product/ISBN"/></p>62 <p><xsl:value-of select = "product/price"/></p>63 <p>64 <form method = "post" action = "UpdateCart">65 <input type = "text" size = "2" 66 name = "{product/ISBN}" 67 value = "{quantity}"/>68 <input type = "submit" value = "Update"/>69 </form>70 </p>

Apply the xsl:template for orderProduct elements to produce an unordered list of product information.

This form enables the customer to check out of the online store to place the order.

This form enables the customer to update the quantity of a particular product in the shopping cart.

Page 37: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.9 ViewCartServlet XSL transformation for I-mode browsers (cHTML/viewCart.xsl).

Lines 72-76

Program output

71 <p>72 <form method = "post" action = "RemoveFromCart">73 <input type = "hidden" name = "ISBN"74 value = "{product/ISBN}"/>75 <input type = "submit" value = "Remove"/>76 </form>77 </p>78 <br/>79 </li>80 </xsl:template>81 </xsl:stylesheet>

This form enables the customer to remove a product from the shopping cart.

Page 38: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.10 ViewCartServlet XSL transformation for WML browsers (WML/viewCart.xsl).

Lines 20-22

Lines 26-49

1 <?xml version = "1.0"?>2 3 <xsl:stylesheet version = "1.0"4 xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">5 6 <xsl:output method = "xml" omit-xml-declaration = "no" 7 doctype-system = "http://www.wapforum.org/DTD/wml_1.1.xml"8 doctype-public = "-//WAPFORUM//DTD WML 1.1//EN"/>9 10 <xsl:include href = "/XSLT/WML/error.xsl"/>11 12 <xsl:template match = "cart">13 <wml>14 15 <card title = "Shopping Cart">16 <do type = "prev">17 <prev/>18 </do>19 20 <do type = "accept" label = "Check Out">21 <go href = "Checkout" method = "post"/>22 </do>23 24 <p><em>Shopping Cart</em></p>25 26 <p>27 Your total: $<xsl:value-of select = "@total"/> 28 29 <table columns = "2">30 <tr>31 <td>Title</td>32 <td>Price</td>33 </tr> 34 35 <xsl:for-each select = "orderProduct">

Enable the user to check out of the online store to place the order.

Mark up the list of products in the shopping cart.

Page 39: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.10 ViewCartServlet XSL transformation for WML browsers (WML/viewCart.xsl).

Lines 54-63

Lines 65-80

36 <tr>37 <td>38 <a href = "#ISBN{product/ISBN}">39 <xsl:value-of select = "product/title"/>40 </a>41 </td> 42 <td>43 $<xsl:value-of select = "product/price"/>44 </td>45 </tr>46 </xsl:for-each>47 48 </table>49 </p>50 51 </card>52 53 <xsl:for-each select = "orderProduct" >54 <card id = "ISBN{product/ISBN}">55 <do label = "OK" type = "prev"><prev/></do>56 <do label = "Change Quant" type = "options">57 <go href = "#quant{product/ISBN}"/>58 </do>59 <p><xsl:value-of select = "product/title"/></p>60 <p>Quantity: <xsl:value-of select = "quantity"/></p>61 <p><xsl:value-of select = "product/author"/></p>62 <p><xsl:value-of select = "product/ISBN"/></p>

63 </card>64 65 <card id = "quant{product/ISBN}">66 <p>Enter new quantity67 <input name = "quantity" emptyok = "false"68 type = "text" format = "*n"/>69 </p>

Display information about a single product.

Provide an interface for changing the quantity of a particular product in the shopping cart.

Page 40: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.10 ViewCartServlet XSL transformation for WML browsers (WML/viewCart.xsl).

70 71 <do type = "accept" label = "Update Quantity">72 <go href = "UpdateCart" method = "post">73 <postfield name = "{product/ISBN}" 74 value = "$quantity"/>75 </go>76 </do>77 78 <do type = "prev" label = "Cancel"><prev/></do>79 80 </card>81 </xsl:for-each>82 83 </wml> 84 </xsl:template>85 </xsl:stylesheet>

Page 41: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.10 ViewCartServlet XSL transformation for WML browsers (WML/viewCart.xsl).

Program output

Page 42: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3.3 RemoveFromCartServlet

• RemoveFromCartServlet– Remove products from shopping cart

Page 43: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig.18.11 RemoveFromCartServlet for removing products from shopping cart.

Line 34

1 // RemoveFromCartServlet.java2 // RemoveFromCartServlet removes a Product from the Customer's 3 // ShoppingCart.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages 7 import java.io.*;8 9 // Java extension packages10 import javax.servlet.*;11 import javax.servlet.http.*;12 13 // third-party packages14 import org.w3c.dom.*;15 16 // Deitel packages17 import com.deitel.advjhtp1.bookstore.model.*;18 import com.deitel.advjhtp1.bookstore.ejb.*;19 import com.deitel.advjhtp1.bookstore.exceptions.*;20 21 public class RemoveFromCartServlet extends XMLServlet {22 23 // respond to HTTP post requests24 public void doPost( HttpServletRequest request,25 HttpServletResponse response )26 throws ServletException, IOException27 {28 Document document = getDocumentBuilder().newDocument();29 30 // remove Product from ShoppingCart31 try {32 33 // get ISBN of Product to be removed34 String isbn = request.getParameter( "ISBN" ); 35

Retrieves from the HttpSession the ISBN of the product that the customer would like to remove from the shopping cart.

Page 44: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig.18.11 RemoveFromCartServlet for removing products from shopping cart.

Lines 39-40

Line 44

Line 48

Lines 53-61

36 // get Customer's ShoppingCart from session37 HttpSession session = request.getSession();38 39 ShoppingCart shoppingCart = 40 ( ShoppingCart ) session.getAttribute( "cart" );41 42 // if ShoppingCart is not null, remove Product43 if ( shoppingCart != null )44 shoppingCart.removeProduct( isbn );45 46 // redirect Customer to ViewCartServlet to view47 // the contents of ShoppingCart48 response.sendRedirect( "ViewCart" ); 49 50 } // end try51 52 // handle exception if Product not found in ShoppingCart53 catch ( ProductNotFoundException productException ) {54 productException.printStackTrace();55 56 // append error message to XML document57 document.appendChild( buildErrorMessage( 58 document, productException.getMessage() ) );59 60 writeXML( request, response, document ); 61 }62 63 } // end method doGet64 }

Obtain the ShoppingCart remote reference from the HttpSession object.

Invokes ShoppingCart method removeProduct if the ShoppingCart reference is not null.

Redirects the client to ViewCartServlet to display the results of removing the product from the shopping cart.

Catch exception and generate an error message to inform the user of the problem.

Page 45: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3.4 UpdateCartServlet

• UpdateCartServlet– Change the quantities of products in the shopping cart

Page 46: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.12 UpdateCartServlet for updating quantities of products in shopping cart.

1 // UpdateCartServlet.java2 // UpdateCartServlet updates the quantity of a Product in the 3 // Customer's ShoppingCart.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 import java.util.*;9 10 // Java extension packages11 import javax.servlet.*;12 import javax.servlet.http.*;13 14 // third-party packages15 import org.w3c.dom.*;16 17 // Deitel packages18 import com.deitel.advjhtp1.bookstore.model.*;19 import com.deitel.advjhtp1.bookstore.ejb.*;20 import com.deitel.advjhtp1.bookstore.exceptions.*;21 22 public class UpdateCartServlet extends XMLServlet {23 24 // respond to HTTP post requests25 public void doPost( HttpServletRequest request,26 HttpServletResponse response )27 throws ServletException, IOException28 {29 Document document = getDocumentBuilder().newDocument();30 31 // update quantity of given Product in ShoppingCart32 try {33 34 // get Customer's ShoppingCart from session 35 HttpSession session = request.getSession( false );

Page 47: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.12 UpdateCartServlet for updating quantities of products in shopping cart.

Lines 37-38

Line 41

Lines 50-51

Lines 55-56

Line 61

36 37 ShoppingCart shoppingCart = ( ShoppingCart )38 session.getAttribute( "cart" );39 40 // get Enumeration of parameter names41 Enumeration parameters = request.getParameterNames();42 43 // update quantity for each ISBN parameter44 while ( parameters.hasMoreElements() ) {45 46 // get ISBN of Product to be updated47 String ISBN = ( String ) parameters.nextElement();48 49 // get new quantity for Product50 int newQuantity = Integer.parseInt( 51 request.getParameter( ISBN ) );52 53 // set quantity in ShoppingCart for Product54 // with given ISBN55 shoppingCart.setProductQuantity( ISBN, 56 newQuantity );57 }58 59 // redirect Customer to ViewCartServlet to view60 // contents of ShoppingCart61 response.sendRedirect( "ViewCart" );62 63 } // end try64 65 // handle exception if Product not found in ShoppingCart66 catch ( ProductNotFoundException productException ) {67 productException.printStackTrace();68 69 document.appendChild( buildErrorMessage( 70 document, productException.getMessage() ) );

Retrieve the customer’s ShoppingCart from the HttpSession object.

Retrieves an Enumeration of parameter names from HttpServletRequest object.

Obtain the newQuantity for the product from the request parameter.

Set the quantity for each product in the shopping cart.

Redirects the client to ViewCartServlet to show the updates to the shopping cart.

Page 48: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.12 UpdateCartServlet for updating quantities of products in shopping cart.

71 72 writeXML( request, response, document ); 73 }74 75 } // end method doGet76 }

Page 49: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.3.5 CheckoutServlet

• CheckoutServlet– Complete the customer’s order

Page 50: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.13 CheckoutServlet for placing Orders.

Lines 32-33

1 // CheckOutServlet.java2 // CheckOutServlet allows a Customer to checkout of the online3 // store to purchase the Products in the ShoppingCart.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 9 // Java extension packages10 import javax.servlet.*;11 import javax.servlet.http.*;12 13 // third-party packages14 import org.w3c.dom.*;15 16 // Deitel packages17 import com.deitel.advjhtp1.bookstore.model.*;18 import com.deitel.advjhtp1.bookstore.ejb.*;19 import com.deitel.advjhtp1.bookstore.exceptions.*;20 21 public class CheckoutServlet extends XMLServlet {22 23 // respond to HTTP post requests24 public void doPost( HttpServletRequest request,25 HttpServletResponse response )26 throws ServletException, IOException27 {28 Document document = getDocumentBuilder().newDocument();29 HttpSession session = request.getSession(); 30 31 // get Customer's userID from session32 String userID = ( String ) 33 session.getAttribute( "userID" );34

Retrieve the customer’s userID from the HttpSession.

Page 51: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.13 CheckoutServlet for placing Orders.

Lines 39-40

Line 51

Line 54

Lines 57-58

Lines 60-70

35 // get ShoppingCart and check out36 try {37 38 // get Customer's ShoppingCart from session39 ShoppingCart shoppingCart = ( ShoppingCart )40 session.getAttribute( "cart" );41 42 // ensure Customer has a ShoppingCart43 if ( shoppingCart == null )44 throw new ProductNotFoundException( "Your " +45 "ShoppingCart is empty." );46 47 // ensure userID is neither null nor empty48 if ( !( userID == null || userID.equals( "" ) ) ) {49 50 // invoke checkout method to place Order51 Order order = shoppingCart.checkout( userID );52 53 // get orderID for Customer's Order54 Integer orderID = ( Integer ) order.getPrimaryKey();55 56 // go to ViewOrder to show completed order57 response.sendRedirect( "ViewOrder?orderID=" + 58 orderID );59 }60 else {61 // userID was null, indicating Customer is 62 // not logged in63 String error = "You are not logged in.";64 65 // append error message to XML document66 document.appendChild( buildErrorMessage( document,67 error ) ); 68 69 writeXML( request, response, document );

Obtain a remote reference to the customer’s ShoppingCart from the session object.

Invokes ShoppingCart method checkout to place the order.Gets the orderID for

the Order.

Redirect the client to ViewOrderServlet.

Generates an error message indicating that the customer is not logged in.

Page 52: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.13 CheckoutServlet for placing Orders.

Lines 75-83

70 }71 72 } // end try73 74 // handle exception if Product not found in ShoppingCart75 catch ( ProductNotFoundException productException ) {76 productException.printStackTrace();77 78 // append error message to XML document79 document.appendChild( buildErrorMessage( 80 document, productException.getMessage() ) );81 82 writeXML( request, response, document );83 }84 85 } // end method doPost86 }

Catch exception if the shopping cart is empty.

Page 53: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.13 CheckoutServlet for placing Orders.

Program output

Page 54: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.13 CheckoutServlet for placing Orders.

Program output

Page 55: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.4 Product Catalog Servlets

• Product catalog servlets– Provide an online catalog– GetAllProductsServlet– ProductSearchServlet

Page 56: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.4.1 GetAllProductsServlets

• GetAllProductsServlets– Provides a list of products available online

Page 57: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.14 GetAllProductsServlet for viewing the product catalog.

1 // GetAllProductsServlet.java2 // GetAllProductsServlet retrieves a list of all Products 3 // available in the store and presents the list to the client.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages 7 import java.io.*;8 import java.util.*;9 10 // Java extension packages11 import javax.servlet.*;12 import javax.servlet.http.*;13 import javax.rmi.*;14 import javax.naming.*;15 import javax.ejb.*;16 17 // third-party packages18 import org.w3c.dom.*;19 20 // Deitel packages21 import com.deitel.advjhtp1.bookstore.model.*;22 import com.deitel.advjhtp1.bookstore.ejb.*;23 24 public class GetAllProductsServlet extends XMLServlet {25 26 // respond to HTTP get requests27 public void doGet( HttpServletRequest request,28 HttpServletResponse response )29 throws ServletException, IOException30 {31 Document document = getDocumentBuilder().newDocument();32 33 // generate Product catalog34 try { 35 InitialContext context = new InitialContext();

Page 58: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.14 GetAllProductsServlet for viewing the product catalog.

Lines 35-44

Lines 47-48

Lines 58-70

Lines 64-65

Lines 68-69

36 37 // look up Product EJB38 Object object = 39 context.lookup( "java:comp/env/ejb/Product" );40 41 // get ProductHome interface to find all Products42 ProductHome productHome = ( ProductHome ) 43 PortableRemoteObject.narrow( object, 44 ProductHome.class );45 46 // get Iterator for Product list47 Iterator products = 48 productHome.findAllProducts().iterator();49 50 // create root of XML document51 Element rootElement = 52 document.createElement( "catalog" );53 54 // append catalog Element to XML document55 document.appendChild( rootElement );56 57 // add each Product to the XML document58 while ( products.hasNext() ) {59 Product product = ( Product )60 PortableRemoteObject.narrow( products.next(),61 Product.class );62 63 // get ProductModel for current Product64 ProductModel productModel = 65 product.getProductModel();66 67 // add an XML element to document for Product68 rootElement.appendChild( 69 productModel.getXML( document ) ); 70 }

Retrieve a remote reference to the Product EJB, which represents a product in the store.

Method findAllProducts of interface ProductHome returns a Collection of Product EJBs, each of which represents a single product.

Iterate through the Collection of products to build an XML document that contains information about each product.

Obtain a ProductModel for each product.

Retrieve each product’s XML description.

Page 59: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.14 GetAllProductsServlet for viewing the product catalog.

Lines 98-100

71 72 } // end try73 74 // handle exception when looking up Product EJB75 catch ( NamingException namingException ) { 76 namingException.printStackTrace(); 77 78 String error = "The Product EJB was not found in " +79 "the JNDI directory.";80 81 // append error message to XML document82 document.appendChild( buildErrorMessage(83 document, error ) );84 }85 86 // handle exception when a Product cannot be found87 catch ( FinderException finderException ) { 88 finderException.printStackTrace(); 89 90 String error = "No Products found in the store.";91 92 // append error message to XML document93 document.appendChild( buildErrorMessage( 94 document, error ) );95 }96 97 // ensure content is written to client98 finally { 99 writeXML( request, response, document ); 100 }101 102 } // end method doGet103 }

The finally block presents the content to the client using method writeXML.

Page 60: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.14 GetAllProductsServlet for viewing the product catalog. Program output

Page 61: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.14 GetAllProductsServlet for viewing the product catalog.

Program output

Page 62: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.4.2 GetProductServlet

• GetProductServlet– Detailed information about a product

Page 63: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.15 GetProductServlet for viewing product details.

1 // GetProductServlet.java2 // GetProductServlet retrieves the details of a Product and 3 // presents them to the customer.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 9 // Java extension packages10 import javax.servlet.*;11 import javax.servlet.http.*;12 import javax.naming.*;13 import javax.ejb.*;14 import javax.rmi.*;15 16 // third-party packages17 import org.w3c.dom.*;18 19 // Deitel packages20 import com.deitel.advjhtp1.bookstore.model.*;21 import com.deitel.advjhtp1.bookstore.ejb.*;22 23 public class GetProductServlet extends XMLServlet {24 25 public void doGet( HttpServletRequest request,26 HttpServletResponse response )27 throws ServletException, IOException28 {29 Document document = getDocumentBuilder().newDocument();30 31 // get ISBN from request object32 String isbn = request.getParameter( "ISBN" );33

Page 64: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.15 GetProductServlet for viewing product details.

Lines 39-45

Lines 48-49

Lines 59-64

34 // generate XML document with Product details35 try {36 InitialContext context = new InitialContext();37 38 // look up Product EJB39 Object object = 40 context.lookup( "java:comp/env/ejb/Product" );41 42 // get ProductHome interface to find Product43 ProductHome productHome = ( ProductHome ) 44 PortableRemoteObject.narrow( 45 object, ProductHome.class );46 47 // find Product with given ISBN48 Product product = 49 productHome.findByPrimaryKey( isbn );50 51 // create XML document root Element52 Node rootNode = 53 document.createElement( "bookstore" );54 55 // append root Element to XML document56 document.appendChild( rootNode );57 58 // get Product details as a ProductModel59 ProductModel productModel = 60 product.getProductModel();61 62 // build an XML document with Product details63 rootNode.appendChild( 64 productModel.getXML( document ) );65 66 } // end try67

Retrieve a reference to the ProductHome interface.

Invoke ProductHome interface method findByPrimaryKey to obtain the Product EJB for the given ISBN.

Obtain the details of the product as a ProductModel and use method getXML to generate the XML content for the client.

Page 65: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.15 GetProductServlet for viewing product details.

68 // handle exception when looking up Product EJB69 catch ( NamingException namingException ) { 70 namingException.printStackTrace(); 71 72 String error = "The Product EJB was not found in " +73 "the JNDI directory.";74 75 document.appendChild( buildErrorMessage(76 document, error ) );77 }78 79 // handle exception when Product is not found80 catch ( FinderException finderException ) { 81 finderException.printStackTrace(); 82 83 String error = "The Product with ISBN " + isbn +84 " was not found in our store.";85 86 document.appendChild( buildErrorMessage( 87 document, error ) );88 }89 90 // ensure content is written to client91 finally { 92 writeXML( request, response, document ); 93 }94 95 } // end method doGet96 }

Page 66: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.15 GetProductServlet for viewing product details.

Program output

Page 67: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.15 GetProductServlet for viewing product details.

Program output

Page 68: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.4.3 ProductSearchServlet

• ProductSearchServlet – Search the database for products

Page 69: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.16 ProductSearchServlet for searching product catalog.

Lines 34-35

1 // ProductSearchServlet.java2 // ProductSearchServlet allows a Customer to search through 3 // the store for a particular Product.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 import java.util.*;9 10 // Java extension packages11 import javax.servlet.*;12 import javax.servlet.http.*;13 import javax.naming.*;14 import javax.ejb.*;15 import javax.rmi.PortableRemoteObject;16 17 // third-party packages18 import org.w3c.dom.*;19 20 // Deitel packages21 import com.deitel.advjhtp1.bookstore.model.*;22 import com.deitel.advjhtp1.bookstore.ejb.*;23 24 public class ProductSearchServlet extends XMLServlet {25 26 // respond to HTTP get requests27 public void doGet( HttpServletRequest request, 28 HttpServletResponse response )29 throws ServletException, IOException30 { 31 Document document = getDocumentBuilder().newDocument();32 33 // get the searchString from the request object34 String searchString = "%" + 35 request.getParameter( "searchString" ) + "%";

Get the searchString from the request object.

Page 70: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.16 ProductSearchServlet for searching product catalog.

Lines 50-51

Lines 58-69

36 37 // find Product using Product EJB38 try {39 InitialContext context = new InitialContext();40 41 // look up Product EJB42 Object object = 43 context.lookup( "java:comp/env/ejb/Product" );44 45 ProductHome productHome = ( ProductHome ) 46 PortableRemoteObject.narrow( 47 object, ProductHome.class );48 49 // find Products that match searchString50 Iterator products = productHome.findByTitle( 51 searchString ).iterator();52 53 // create catalog document element54 Node rootNode = document.appendChild( 55 document.createElement( "catalog" ) );56 57 // generate list of matching products58 while ( products.hasNext() ) {59 Product product = ( Product )60 PortableRemoteObject.narrow( products.next(),61 Product.class );62 63 ProductModel productModel = product.getProductModel();64 65 // append XML element to the document for the 66 // current Product67 rootNode.appendChild( 68 productModel.getXML( document ) );69 }70

Create an Iterator to iterate through the list of products returned by the search.

Add an XML representation to the XML document for each product found.

Page 71: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.16 ProductSearchServlet for searching product catalog.

71 } // end try72 73 // handle exception when looking up Product EJB74 catch ( NamingException namingException ) { 75 namingException.printStackTrace(); 76 77 String error = "The Product EJB was not found in " +78 "the JNDI directory.";79 80 document.appendChild( buildErrorMessage(81 document, error ) );82 }83 84 // handle exception when Product is not found85 catch ( FinderException finderException ) { 86 finderException.printStackTrace(); 87 88 String error = "No Products match your search.";89 90 document.appendChild( buildErrorMessage( 91 document, error ) );92 }93 94 // ensure content is written to client95 finally { 96 writeXML( request, response, document ); 97 }98 99 } // end method doGet100 }

Page 72: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.16 ProductSearchServlet for searching product catalog.

Program output

Page 73: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.16 ProductSearchServlet for searching product catalog.

Program output

Page 74: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.5 Customer Management Servlets

• RegisterServlet– Customer registration

• LoginServlet– Log in page

• ViewOrderHistoryServlet– Order history information

• GetLostPasswordServlet– Remind passwords

Page 75: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.5.1 RegisterServlet

• RegisterServlet– Process registration forms

Page 76: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.17 RegisterServlet for registering new Customers.

Line 34

1 // RegisterServlet.java2 // RegisterServlet processes the Customer registration form 3 // to register a new Customer.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 import java.util.*;9 10 // Java extension packages11 import javax.servlet.*;12 import javax.servlet.http.*;13 import javax.ejb.*;14 import javax.naming.*;15 import javax.rmi.*;16 17 // third-party packages18 import org.w3c.dom.*;19 20 // Deitel packages21 import com.deitel.advjhtp1.bookstore.model.*;22 import com.deitel.advjhtp1.bookstore.ejb.*;23 24 public class RegisterServlet extends XMLServlet {25 26 // respond to HTTP post requests27 public void doPost( HttpServletRequest request,28 HttpServletResponse response )29 throws ServletException, IOException30 {31 Document document = getDocumentBuilder().newDocument();32 33 // create CustomerModel to store registration data34 CustomerModel customerModel = new CustomerModel(); 35

Create a CustomerModel instance.

Page 77: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.17 RegisterServlet for registering new Customers.

Lines 38-125

36 // set properties of CustomerModel using values37 // passed through request object 38 customerModel.setUserID( request.getParameter( 39 "userID" ) );40 41 customerModel.setPassword( request.getParameter( 42 "password" ) );43 44 customerModel.setPasswordHint( request.getParameter( 45 "passwordHint" ) );46 47 customerModel.setFirstName( request.getParameter( 48 "firstName" ) );49 50 customerModel.setLastName( request.getParameter( 51 "lastName" ) );52 53 // set credit card information54 customerModel.setCreditCardName( request.getParameter( 55 "creditCardName" ) );56 57 customerModel.setCreditCardNumber( request.getParameter( 58 "creditCardNumber" ) );59 60 customerModel.setCreditCardExpirationDate( 61 request.getParameter( "creditCardExpirationDate" ) );62 63 // create AddressModel for billing address64 AddressModel billingAddress = new AddressModel();65 66 billingAddress.setFirstName( request.getParameter( 67 "billingAddressFirstName" ) );68 69 billingAddress.setLastName( request.getParameter( 70 "billingAddressLastName" ) );

Uses the parameter values received from the client to populate the model with details about the customer.

Page 78: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.17 RegisterServlet for registering new Customers.

71 72 billingAddress.setStreetAddressLine1( 73 request.getParameter( "billingAddressStreet1" ) );74 75 billingAddress.setStreetAddressLine2( 76 request.getParameter( "billingAddressStreet2" ) );77 78 billingAddress.setCity( request.getParameter( 79 "billingAddressCity" ) );80 81 billingAddress.setState( request.getParameter( 82 "billingAddressState" ) );83 84 billingAddress.setZipCode( request.getParameter( 85 "billingAddressZipCode" ) );86 87 billingAddress.setCountry( request.getParameter( 88 "billingAddressCountry" ) );89 90 billingAddress.setPhoneNumber( request.getParameter( 91 "billingAddressPhoneNumber" ) );92 93 customerModel.setBillingAddress( billingAddress );94 95 // create AddressModel for shipping address96 AddressModel shippingAddress = new AddressModel();97 98 shippingAddress.setFirstName( request.getParameter( 99 "shippingAddressFirstName" ) );100 101 shippingAddress.setLastName( request.getParameter( 102 "shippingAddressLastName" ) );103 104 shippingAddress.setStreetAddressLine1( 105 request.getParameter( "shippingAddressStreet1" ) );

Page 79: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.17 RegisterServlet for registering new Customers.

Line 133

106 107 shippingAddress.setStreetAddressLine2( 108 request.getParameter( "shippingAddressStreet2" ) );109 110 shippingAddress.setCity( request.getParameter( 111 "shippingAddressCity" ) );112 113 shippingAddress.setState( request.getParameter( 114 "shippingAddressState" ) );115 116 shippingAddress.setZipCode( request.getParameter( 117 "shippingAddressZipCode" ) );118 119 shippingAddress.setCountry( request.getParameter( 120 "shippingAddressCountry" ) );121 122 shippingAddress.setPhoneNumber( request.getParameter( 123 "shippingAddressPhoneNumber" ) );124 125 customerModel.setShippingAddress( shippingAddress ); 126 127 // look up Customer EJB and create new Customer128 try {129 InitialContext context = new InitialContext();130 131 // look up Customer EJB132 Object object = 133 context.lookup( "java:comp/env/ejb/Customer" );134 135 CustomerHome customerHome = ( CustomerHome ) 136 PortableRemoteObject.narrow( object, 137 CustomerHome.class );138

Looks up the Customer EJB, which represents a customer in the database.

Page 80: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.17 RegisterServlet for registering new Customers.

Lines 141-142

Lines 147-157

Lines 162-172

139 // create new Customer using the CustomerModel with140 // Customer's registration information141 Customer customer = 142 customerHome.create( customerModel );143 144 customerModel = customer.getCustomerModel(); 145 146 // get RequestDispatcher for Login servlet 147 RequestDispatcher dispatcher = 148 getServletContext().getRequestDispatcher( "/Login" );149 150 // set userID and password for Login servlet151 request.setAttribute( "userID", 152 customerModel.getUserID() );153 request.setAttribute( "password", 154 customerModel.getPassword() );155 156 // forward user to LoginServlet157 dispatcher.forward( request, response );158 159 } // end try160 161 // handle exception when looking up Customer EJB162 catch ( NamingException namingException ) { 163 namingException.printStackTrace(); 164 165 String error = "The Customer EJB was not " +166 "found in the JNDI directory.";167 168 document.appendChild( buildErrorMessage(169 document, error ) );170 171 writeXML( request, response, document );172 }173

Create a new customer registration in the database by invoking Customer EJB method create with the newly created CustomerModel object as an argument.

Forward the customer to LoginServlet to log into the store.

Catch a NamingException, which indicates that the CustomerHome interface could not be found in the JNDI directory.

Page 81: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.17 RegisterServlet for registering new Customers.

Lines 175-184

174 // handle exception when creating Customer175 catch ( CreateException createException ) { 176 createException.printStackTrace(); 177 178 String error = "The Customer could not be created";179 180 document.appendChild( buildErrorMessage( 181 document, error ) );182 183 writeXML( request, response, document ); 184 }185 186 } // end method doPost187 }

Catch a CreatException in case the Customer EJB could not be created.

Page 82: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.5.2 LoginServlet

• LoginServlet– Check userID and password

Page 83: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.18 LoginServlet for authenticating registered Customers.

1 // LoginServlet.java2 // LoginServlet that logs an existing Customer into the site.3 package com.deitel.advjhtp1.bookstore.servlets;4 5 // Java core packages6 import java.io.*;7 8 // Java extension packages9 import javax.servlet.*;10 import javax.servlet.http.*;11 import javax.naming.*;12 import javax.ejb.*;13 import javax.rmi.*;14 15 // third-party packages16 import org.w3c.dom.*;17 18 // Deitel packages19 import com.deitel.advjhtp1.bookstore.model.*;20 import com.deitel.advjhtp1.bookstore.ejb.*;21 22 public class LoginServlet extends XMLServlet {23 24 // respond to HTTP post requests25 public void doPost( HttpServletRequest request,26 HttpServletResponse response )27 throws ServletException, IOException28 {29 Document document = getDocumentBuilder().newDocument();30 31 String userID = request.getParameter( "userID" );32 String password = request.getParameter( "password" );33

Page 84: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.18 LoginServlet for authenticating registered Customers.

Lines 39-44

Lines 47-48

Lines 59-69

34 // use Customer EJB to authenticate user35 try {36 InitialContext context = new InitialContext();37 38 // look up Customer EJB39 Object object = 40 context.lookup( "java:comp/env/ejb/Customer" );41 42 CustomerHome customerHome = ( CustomerHome )43 PortableRemoteObject.narrow( object,44 CustomerHome.class );45 46 // find Customer with given userID and password47 Customer customer = 48 customerHome.findByLogin( userID, password );49 50 // get CustomerModel for Customer51 CustomerModel customerModel = 52 customer.getCustomerModel();53 54 // set userID in Customer's session55 request.getSession().setAttribute( "userID", 56 customerModel.getUserID() );57 58 // create login XML element59 Element login = document.createElement( "login" );60 document.appendChild( login );61 62 // add Customer's first name to XML document63 Element firstName = 64 document.createElement( "firstName" );65 66 firstName.appendChild( document.createTextNode(67 customerModel.getFirstName() ) );68

Obtain a reference to the CustomerHome interface.

Invoke CustomerHome method findByLogin, which returns a remote reference to the Customer with the userID and password that the user provided.

Build a simple XML document that indicates the customer has successfully logged into the store.

Page 85: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.18 LoginServlet for authenticating registered Customers.

Lines 74-82

Lines 85-93

69 login.appendChild( firstName );70 71 } // end try72 73 // handle exception when looking up Customer EJB74 catch ( NamingException namingException ) { 75 namingException.printStackTrace(); 76 77 String error = "The Customer EJB was not found in " +78 "the JNDI directory.";79 80 document.appendChild( buildErrorMessage(81 document, error ) );82 }83 84 // handle exception when Customer is not found85 catch ( FinderException finderException ) { 86 finderException.printStackTrace(); 87 88 String error = "The userID and password entered " +89 "were not found.";90 91 document.appendChild( buildErrorMessage( 92 document, error ) );93 }94 95 // ensure content is written to client96 finally { 97 writeXML( request, response, document ); 98 }99 100 } // end method doPost101 }

Catch a NamingException if the Customer EJB cannot be found in the JNDI directory.

Catch a FinderException if no Customer is found that matches the userID and password the user entered.

Page 86: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.18 LoginServlet for authenticating registered Customers.

Program output

Page 87: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.18 LoginServlet for authenticating registered Customers.

Program output

Page 88: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.5.3 ViewOrderHistoryServlet

• ViewOrderHistoryServlet– View orders information in detail

Page 89: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.19 ViewOrderHistoryServlet for viewing customer’s previously placed Orders.

1 // ViewOrderHistoryServlet.java2 // ViewOrderHistoryServlet presents a list of previous Orders3 // to the Customer.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 import java.util.*;9 10 // Java extension packages11 import javax.servlet.*;12 import javax.servlet.http.*;13 import javax.naming.*;14 import javax.rmi.*;15 import javax.ejb.*;16 17 // third-party packages18 import org.w3c.dom.*;19 20 // Deitel packages21 import com.deitel.advjhtp1.bookstore.model.*;22 import com.deitel.advjhtp1.bookstore.ejb.*;23 import com.deitel.advjhtp1.bookstore.exceptions.*;24 25 public class ViewOrderHistoryServlet extends XMLServlet {26 27 // respond to HTTP get requests28 public void doGet( HttpServletRequest request,29 HttpServletResponse response )30 throws ServletException, IOException31 {32 Document document = getDocumentBuilder().newDocument();33 34 HttpSession session = request.getSession();

Page 90: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.19 ViewOrderHistoryServlet for viewing customer’s previously placed Orders.

Lines 51-52

Lines 59-60

Lines 64-70

35 String userID = ( String ) 36 session.getAttribute( "userID" );37 38 // build order history using Customer EJB39 try {40 InitialContext context = new InitialContext();41 42 // look up Customer EJB43 Object object = 44 context.lookup( "java:comp/env/ejb/Customer" );45 46 CustomerHome customerHome = ( CustomerHome )47 PortableRemoteObject.narrow(48 object, CustomerHome.class );49 50 // find Customer with given userID51 Customer customer = 52 customerHome.findByUserID( userID );53 54 // create orderHistory element55 Element rootNode = ( Element ) document.appendChild( 56 document.createElement( "orderHistory" ) );57 58 // get Customer's Order history59 Iterator orderHistory = 60 customer.getOrderHistory().iterator();61 62 // loop through Order history and add XML elements63 // to XML document for each Order64 while ( orderHistory.hasNext() ) {65 OrderModel orderModel = 66 ( OrderModel ) orderHistory.next();67 68 rootNode.appendChild( 69 orderModel.getXML( document ) );

Obtain the Customer EJB for the Customer.

Retrieve an Iterator for the customer’s order history.

Loop through the order history and build the XML document to present to the client.

Page 91: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.19 ViewOrderHistoryServlet for viewing customer’s previously placed Orders.

Lines 74-79

Lines 82-90

Lines 93-101

70 }71 } // end try72 73 // handle exception when Customer has no Order history74 catch ( NoOrderHistoryException historyException ) { 75 historyException.printStackTrace(); 76 77 document.appendChild( buildErrorMessage( document, 78 historyException.getMessage() ) );79 }80 81 // handle exception when looking up Customer EJB82 catch ( NamingException namingException ) { 83 namingException.printStackTrace(); 84 85 String error = "The Customer EJB was not found in " +86 "the JNDI directory.";87 88 document.appendChild( buildErrorMessage(89 document, error ) );90 }91 92 // handle exception when Customer is not found93 catch ( FinderException finderException ) { 94 finderException.printStackTrace(); 95 96 String error = "The Customer with userID " + userID +97 " was not found.";98 99 document.appendChild( buildErrorMessage( 100 document, error ) ); 101 } 102

Catch exceptions and build an error message to display to the customer.

Page 92: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.19 ViewOrderHistoryServlet for viewing customer’s previously placed Orders.

Program output

103 // ensure content is written to client104 finally { 105 writeXML( request, response, document ); 106 }107 108 } // end method doGet109 }

Page 93: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.19 ViewOrderHistoryServlet for viewing customer’s previously placed Orders.

Program output

Page 94: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.5.4 ViewOrderServlet

• ViewOrderServlet– Displays the details of an order

Page 95: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.20 viewOrderServlet for viewing details of an order.

1 // ViewOrderServlet.java2 // ViewOrderServlet presents the contents of a Customer's 3 // Order.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 9 // Java extension packages10 import javax.servlet.*;11 import javax.servlet.http.*;12 import javax.naming.*;13 import javax.ejb.*;14 import javax.rmi.*;15 16 // third-party packages17 import org.w3c.dom.*;18 19 // Deitel packages20 import com.deitel.advjhtp1.bookstore.model.*;21 import com.deitel.advjhtp1.bookstore.ejb.*;22 23 public class ViewOrderServlet extends XMLServlet {24 25 // respond to HTTP get requests26 public void doGet( HttpServletRequest request,27 HttpServletResponse response )28 throws ServletException, IOException29 {30 Document document = getDocumentBuilder().newDocument();31 Integer orderID = null;32

Page 96: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.20 viewOrderServlet for viewing details of an order.

Lines 39-44

Lines 47-48

Line 51

Lines 54-58

Lines 63-71

33 // look up Order EJB and get details of Order with 34 // given orderID35 try {36 InitialContext context = new InitialContext();37 38 // look up Order EJB39 Object object = 40 context.lookup( "java:comp/env/ejb/Order" );41 42 OrderHome orderHome = ( OrderHome )43 PortableRemoteObject.narrow(44 object, OrderHome.class );45 46 // get orderID from request object47 orderID = new Integer( 48 request.getParameter( "orderID" ) );49 50 // find Order with given orderID51 Order order = orderHome.findByPrimaryKey( orderID );52 53 // get Order details as an OrderModel 54 OrderModel orderModel = order.getOrderModel();55 56 // add Order details to XML document57 document.appendChild( 58 orderModel.getXML( document ) );59 60 } // end try61 62 // handle exception when looking up Order EJB63 catch ( NamingException namingException ) { 64 namingException.printStackTrace();65 66 String error = "The Order EJB was not found in " +67 "the JNDI directory.";

Obtain a reference to the CustomerHome interface.

Retrieve the orderID parameter from the request object.

Invokes OrderHome method findByPrimaryKey to obtain a remote reference to the Order with the given orderID.

Get the OrderModel for the Order and append its XML representation to the XML document.

Catch a NamingException, which is thrown from method lookup if the Order EJB cannot be found in the JNDI directory.

Page 97: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.20 viewOrderServlet for viewing details of an order.

Lines 74-82

Line 86

68 69 document.appendChild( buildErrorMessage(70 document, error ) );71 }72 73 // handle exception when Order is not found74 catch ( FinderException finderException ) { 75 finderException.printStackTrace(); 76 77 String error = "An Order with orderID " + orderID +78 " was not found.";79 80 document.appendChild( buildErrorMessage( 81 document, error ) ); 82 } 83 84 // ensure content is written to client85 finally { 86 writeXML( request, response, document ); 87 }88 89 } // end method doGet90 }

Catch a FinderException, which is thrown by method findByPrimaryKey if an Order with the given orderID is not found.

Presents the XML document to the client.

Page 98: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.20 viewOrderServlet for viewing details of an order.

Program output

Page 99: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.20 viewOrderServlet for viewing details of an order.

Program output

Page 100: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall. All rights reserved.

18.5.5 GetPasswordHintServlet

• GetPasswordHintServlet– Help Customers remember their passwords

Page 101: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.21 GetPasswordHintServlet for viewing a Customer’s password hint.

1 // GetPasswordHintServlet.java2 // GetPasswordHintServlet allows a customer to retrieve a 3 // lost password.4 package com.deitel.advjhtp1.bookstore.servlets;5 6 // Java core packages7 import java.io.*;8 9 // Java extension packages10 import javax.servlet.*;11 import javax.servlet.http.*;12 import javax.naming.*;13 import javax.ejb.*;14 import javax.rmi.*;15 16 // third-party packages17 import org.w3c.dom.*;18 19 // Deitel packages20 import com.deitel.advjhtp1.bookstore.model.*;21 import com.deitel.advjhtp1.bookstore.ejb.*;22 23 public class GetPasswordHintServlet extends XMLServlet {24 25 // respond to HTTP get requests26 public void doGet( HttpServletRequest request,27 HttpServletResponse response )28 throws ServletException, IOException29 {30 Document document = getDocumentBuilder().newDocument();31 String userID = request.getParameter( "userID" );32 33 // get password hint from Customer EJB34 try {35 InitialContext context = new InitialContext();

Page 102: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.21 GetPasswordHintServlet for viewing a Customer’s password hint.

Lines 38-47

Line 55

Line 58

36 37 // look up Customer EJB38 Object object = 39 context.lookup( "java:comp/env/ejb/Customer" );40 41 CustomerHome customerHome = ( CustomerHome )42 PortableRemoteObject.narrow( object,43 CustomerHome.class );44 45 // find Customer with given userID46 Customer customer = 47 customerHome.findByUserID( userID );48 49 // create passwordHint element in XML document50 Element hintElement = 51 document.createElement( "passwordHint" );52 53 // add text of passwordHint to XML element54 hintElement.appendChild( document.createTextNode( 55 customer.getPasswordHint() ) );56 57 // append passwordHint element to XML document58 document.appendChild( hintElement );59 60 } // end try61 62 // handle exception when looking up Customer EJB63 catch ( NamingException namingException ) { 64 namingException.printStackTrace(); 65 66 String error = "The Customer EJB was not found in " +67 "the JNDI directory.";68 69 document.appendChild( buildErrorMessage(70 document, error ) );

Look up the CustomerHome interface and retrieve the Customer EJB remote reference.

Customer EJB method getPasswordHint returns the hint the user entered when registering on the site.

Adds the hint to the XML document.

Page 103: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.21 GetPasswordHintServlet for viewing a Customer’s password hint.

71 }72 73 // handle exception when Customer is not found74 catch ( FinderException finderException ) { 75 finderException.printStackTrace(); 76 77 String error = "No customer was found with userID " +78 userID + ".";79 80 document.appendChild( buildErrorMessage( 81 document, error ) );82 }83 84 // ensure content is written to client85 finally { 86 writeXML( request, response, document ); 87 }88 89 } // end method doGet90 }

Page 104: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.21 GetPasswordHintServlet for viewing a Customer’s password hint.

Program output

Page 105: 2002 Prentice Hall. All rights reserved. Chapter 18 Enterprise Java Case Study: Presentation and Controller Logic Outline 18.1 Introduction 18.2 XMLServlet

2002 Prentice Hall.All rights reserved.

Outline

Fig. 18.21 GetPasswordHintServlet for viewing a Customer’s password hint.

Program output