Sample Program: Writing a Servlet Chain for the BookShoppingServlet

Sample Program: Writing a Servlet Chain for the BookShoppingServlet

Listing 4.1 contains snippets of the BookShoppingServlet code for initializing the ServletContext object, adding the new Checkout button to the View Cart page, and servlet chaining. The BookCheckOutServlet will be listed completely and explained in detail later.

Listing 4.1 Code Snippets for BookShoppingServlet.java
 ...     public void init(ServletConfig config) throws ServletException {         super.init(config);         sc = getServletConfig().getServletContext(); ...     }//end of init ...     public void doSessionUsingHttpSession(PrintWriter outputObject,                    HttpServletRequest req, HttpServletResponse res)     throws ServletException, IOException{ ...         if(clickedButton.equals("view"))         { ...             //changed here to add button for checkout             outputObject.println("<p align =\"center\"><INPUT type=\"submit\"                     name=\"buttonName\" value=\"Empty Shopping Cart\">&nbsp;&nbsp;                     <INPUT type=\"submit\" name=\"buttonName\"                     value=\"Checkout\"></p>");             outputObject.println("</FORM>");         } ...         //added here to check for Checkout button         else if(clickedButton.equals("Checkout")){             //path given in this request dispatcher is relative to the             //web application             //you can define path relative to current servlet by using servlet                     request.getRequestDispatcher(String path)             RequestDispatcher rd =                               sc.getRequestDispatcher("/BookCheckOutServlet");             //using include method here because the headerzone has already             //been written.             //if you use forward here, you can get IllegalStateException             rd.include(req,res);         } ...         }     public void writeViewCartZone(PrintWriter outputObject, int book1Qty,             int book2Qty, int book3Qty){         double totBook1Price =                      Utility.getRoundedAmount(book1Qty * book1.getBookPrice());         double totBook2Price =                      Utility.getRoundedAmount(book2Qty * book2.getBookPrice());         double totBook3Price =                      Utility.getRoundedAmount(book3Qty * book3.getBookPrice());         double grandTotal = totBook1Price + totBook2Price + totBook3Price;         //adding these to the Servlet context         sc.setAttribute("totBook1Price", new Double(totBook1Price));         sc.setAttribute("totBook2Price", new Double(totBook2Price));         sc.setAttribute("totBook3Price", new Double(totBook3Price));         sc.setAttribute("grandTotal", new Double(grandTotal));         sc.setAttribute("book1Qty",new Integer(book1Qty));         sc.setAttribute("book2Qty",new Integer(book2Qty));         sc.setAttribute("book3Qty",new Integer(book3Qty));     } ... 

The first part of the code is the init() method. You obtain the ServletContext object reference in the init() method using the following code:

     public void init(ServletConfig config) throws ServletException      {         super.init(config);         sc = getServletConfig().getServletContext(); ...     } 

Once the ServletContext is obtained, servlet chaining can be performed anytime in the BookShoppingServlet.

Next you'll add the Checkout button to the View Cart page. The following code snippet shows how the BookShoppingServlet obtains the reference to the RequestDispatcher object by invoking the getRequestDispatcher() method of the ServletContext when the user clicks the Checkout button in the browser page. After this, the BookShoppingServlet delegates control to the CheckOutServlet using the include() method of the RequestDispatcher object:

 RequestDispatcher rd =                     sc.getRequestDispatcher("/BookCheckOutServlet"); //using include method here because the headerzone has //already been written. //if you use forward here, you can get IllegalStateException rd.include(req,res); 

The include() method is used rather than forward() since the header zone data of the Checkout page has already been sent to the output stream. Recall that forward() throws an IllegalStateException when data has already been written to the servlet output stream by the servlet containing the forward() method call.

In the final code snippet, the data is passed from the BookShoppingServlet to the BookCheckOutServlet, using the ServletContext as the placeholder for passing the data. The setAttribute() method is used to set the data from the BookShoppingServlet into the ServletContext. The statement is shown here:

 //adding these to the Servlet context  sc.setAttribute("totBook1Price", new Double(totBook1Price)); sc.setAttribute("totBook2Price", new Double(totBook2Price)); sc.setAttribute("totBook3Price", new Double(totBook3Price)); sc.setAttribute("grandTotal", new Double(grandTotal)); sc.setAttribute("book1Qty",new Integer(book1Qty)); sc.setAttribute("book2Qty",new Integer(book2Qty)); sc.setAttribute("book3Qty",new Integer(book3Qty)); 

Now you will study the BookCheckOutServlet program, shown in Listing 4.2.

Listing 4.2 BookCheckOutServlet.java
 /******************************************************************************   * Class Name:BookCheckOutServlet   * Extends:HttpServlet   * Description:Shopping Cart Application Using cookies, and demonstrates   *             request forwarding.   *             This servlet displays the chosen books, and then proceeds to   *             checkout the books purchased.   * @author Mandar S. Chitnis, Lakshmi AM.       @version 1.1   * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.servlets; //import the utils package import com.sams.learnweblogic7.utils.*; //importing standard servlet packages import javax.servlet.*; import javax.servlet.http.*; //import io,util and math packages import java.io.*; import java.util.*; import java.math.*; public class BookCheckOutServlet extends HttpServlet { //defining global variables to be used in this servlet     Book book1;     Book book2;     Book book3;     PrintWriter out;     ServletContext sc;     //Method corresponding to get request of HTML     //Internally calls doPost, passing request & response objects     public void doGet(HttpServletRequest req, HttpServletResponse res)                                  throws ServletException, IOException{         doPost(req,res);     }     //Method corresponding to post request of HTML, & called by doGet() method     //Gets the book objects from servlet context     //Calculates the total price for the books purchased     //Creates the jsp and forwards this request to a jsp     public void doPost(HttpServletRequest req, HttpServletResponse res)                                   throws ServletException, IOException{         //display the books chosen by accessing the book objects from         //servlet context         sc = getServletConfig().getServletContext();         out = res.getWriter();         book1 = (Book)sc.getAttribute("book1");         book2 = (Book)sc.getAttribute("book2");         book3 = (Book)sc.getAttribute("book3");         double totBook1Price =                       ((Double)sc.getAttribute("totBook1Price")).doubleValue();         double totBook2Price =                       ((Double)sc.getAttribute("totBook2Price")).doubleValue();         double totBook3Price =                       ((Double)sc.getAttribute("totBook3Price")).doubleValue();         double grandTotal =                       ((Double)sc.getAttribute("grandTotal")).doubleValue();         int book1Qty = ((Integer)sc.getAttribute("book1Qty")).intValue();         int book2Qty = ((Integer)sc.getAttribute("book2Qty")).intValue();         int book3Qty = ((Integer)sc.getAttribute("book3Qty")).intValue();         out.println("<FORM name=\"viewcart\" action=\"/ShoppingApp/                 BookShoppingServlet\" method=\"get\">");         out.println("<TABLE width = 100%>");         out.println("<CENTER><B>Your Shopping Cart Contains:</B></CENTER><BR>");         out.println("<TR><TH>&nbsp;</TH><TH>Book Name and description</TH>                 <TH>Book Price</TH><TH>Qty</TH><TH>Total for each book                         </TH></TR>");         out.println("<TR bgcolor='#cccc99'><TD><img src="/books/2/96/1/html/2/+book1.getImagePath()                 +"></TD><TD align='left'><b>"+book1.getBookName()+"</b><BR>"                 +book1.getBookDescription()+"</TD><TD align='left'>                 $"+book1.getBookPrice()+"</TD><TD align                 ='center'>"+book1Qty+"</TD><TD                 align='center'>$"+totBook1Price+"</FONT></TD></TR>");         out.println("<TR bgcolor='#eeeeee'><TD><img src="/books/2/96/1/html/2/+book2.getImagePath()                 +"></TD><TD align='left'><b>"+book2.getBookName()+"</b><BR>"                 +book2.getBookDescription()+"</TD><TD align='left'>                 $"+book2.getBookPrice()+"</TD><TD align                 ='center'>"+book2Qty+"</TD><TD                 align='center'>$"+totBook2Price+"</FONT></TD></TR>");         out.println("<TR bgcolor='#cccc99'><TD><img src="/books/2/96/1/html/2/+book3.getImagePath()                 +"></TD><TD align='left'><b>"+book3.getBookName()+"</b><BR>"                 +book3.getBookDescription()+"</TD><TD align='left'>                 $"+book3.getBookPrice()+"</TD><TD align                 ='center'>"+book3Qty+"</TD><TD                 align='center'>$"+totBook3Price+"</FONT></TD></TR>");         out.println("<TR bgcolor='#eeeeee'><TD>&nbsp;</TD><TD>&nbsp;</TD>                 <TD>&nbsp;</TD><TD>&nbsp;</TD><TD align='left'>                 <b>Total = $"+grandTotal+"</b></FONT></TD></TR>");         out.println("</TD></TR></TABLE>");         out.println("<BR><BR><HR><BR><BR>");         out.println("<center><b>Please input your credit card details</b>                 </center>");         out.println("<b>Name on Card : </b><INPUT type=\"TEXT\"                 name=\"CardHolderName\"><BR>");         out.println("<b>Type of Card : </b><SELECT><OPTION value=\"Visa\">Visa                 </OPTION><OPTION value=\"MasterCard\">Master Card                 </OPTION></SELECT><BR>");         out.println("<b>Credit Card No: </b><INPUT type=\"TEXT\"                 name\"CardNumber\"><BR>");         out.println("<b>Expiry date : </b>MM <INPUT type=\"TEXT\"                name\"ExpMonth\" size=2> / YY<INPUT type=\"TEXT\"                name\"ExpMonth\"size=2><BR><BR>");         out.println("<INPUT type=\"button\" NAME=\"buttonName\"                 Value=\"Order Disabled for now\">&nbsp;&nbsp;");         out.println("<INPUT type=\"submit\" NAME=\"buttonName\"                 Value=\"Empty Shopping Cart\"><BR>");         out.println("<BR><BR><HR><BR><BR>");         out.println("</FORM>");         //calling the write FooterZone         Utility.writeFooterZone(out);     } } 

The BookCheckOutServlet is a fairly simple servlet program on the lines of the BookShoppingServlet program. The only interesting code snippet that you need to focus on is the section where the data that is set in the ServletContext by the calling BookShoppingServlet servlet is retrieved using the getAttribute() method:

 public void doPost(HttpServletRequest req, HttpServletResponse res)                                throws ServletException, IOException{     //display the books chosen by accessing the book objects     //from servlet context.     sc = getServletConfig().getServletContext();     out = res.getWriter();     book1 = (Book)sc.getAttribute("book1");     book2 = (Book)sc.getAttribute("book2");     book3 = (Book)sc.getAttribute("book3");     double totBook1Price =               ((Double)sc.getAttribute("totBook1Price")).doubleValue();     double totBook2Price =                   ((Double)sc.getAttribute("totBook2Price")).doubleValue();     double totBook3Price =                   ((Double)sc.getAttribute("totBook3Price")).doubleValue();     double grandTotal =                   ((Double)sc.getAttribute("grandTotal")).doubleValue();     int book1Qty = ((Integer)sc.getAttribute("book1Qty")).intValue();     int book2Qty = ((Integer)sc.getAttribute("book2Qty")).intValue();     int book3Qty = ((Integer)sc.getAttribute("book3Qty")).intValue(); 

The data retrieved from the BookShoppingServlet is used in the BookCheckOutServlet and displayed by the browser.

Compile the Program

Use the compile.bat batch file provided to compile the servlets. The batch file compiles the BookShoppingServlet.java and BookCheckOutServlet.java files located in the following directory in your domain:

 applications\ShoppingApp\WEB-INF\classes\com\sams\learnweblogic7\servlets\  

Deploy the Program

Deploy the servlets exactly as discussed in Day 3.

Updating a .war Web Archive File

Add your new servlet to the existing Web archive file for the book-shopping application. To update the .war file, go to the root directory of your Web application at a DOS prompt:

 c:\bea\user_domains\mydomain\applications\ShoppingApp\WEB-INF\  

Then type the following command:

 jar  uv0f ShoppingApp.war .  
Registering Your Servlet in web.xml

You need to register the new servlet BookCheckOutServlet by editing the web.xml file in your deployment directory. In this case, the directory is as follows:

 c:\bea\user_domains\mydomain\applications\ShoppingApp\WEB-INF\  

Add the following tags to the web.xml file:

 <servlet>      <servlet-name>BookCheckOutServlet</servlet-name>     <servlet-class>com.sams.learnweblogic7.servlets.BookCheckOutServlet             </servlet-class> </servlet> 

To register the name by which the servlet can be called from the browser, you can map the servlet to a URL. To do so, add the following tags to the web.xml file:

 <servlet-mapping>      <servlet-name>BookCheckOutServlet</servlet-name>     <url-pattern>/BookCheckOutServlet/*</url-pattern> </servlet-mapping> 

This mapping enables you to execute the BookCheckOutServlet by typing the URL /BookCheckOutServlet in the browser or in the calling servlet during servlet chaining.

Setting WebLogic Server Specific Parameters

No special settings are required for servlet chaining. Hence, you need not modify the weblogic.xml file.

Execute the Program

The View Cart page is displayed after it is invoked from the browser by calling the following URL and clicking the View Cart button:

http://localhost:7001/ShoppingApp/BookShoppingServlet

When the user clicks the Checkout button on the View Cart page, servlet chaining occurs: the BookShoppingServlet delegates control to the BookCheckOutServlet. The BookCheckOutServlet generates the Checkout page, where the user can fill in credit card details and see the items selected in the shopping cart.

Figures 4.1 and 4.2 show the two screens generated by the servlet.

Figure 4.1. View Cart screen of the BookShoppingServlet.

graphics/04fig01.jpg

Figure 4.2. Checkout screen of the BookCheckOutServlet.

graphics/04fig02.jpg



Sams Teach Yourself BEA WebLogic Server 7. 0 in 21 Days
Sams Teach Yourself BEA WebLogic Server 7.0 in 21 Days
ISBN: 0672324334
EAN: 2147483647
Year: 2002
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net