Session Handling: Cookies

Using cookies is one of the most widely used and accepted ways to maintain a session. A cookie is a special tag identifier that your server generates and the browser accepts. Actually, it is a simple data structure consisting of name-value pairs associated with a URL, in this case, the URL to execute the servlet. For maintaining a session, the servlet stores the session identifier and other session data as a text string in the cookie.

After accepting the session cookie, the browser propagates the cookie to your servlet for every request from the browser to the servlet. A servlet can read the cookie and modify its contents at any time. If there is no cookie, the servlet detects a new session, generates a unique session identifier, and sets this value to the cookie. This is then sent back to the browser along with the response HTML page. The browser interprets the response, identifies the cookie, and sets it in the browser. After this, for every request, the browser sends this cookie containing the session identifier to the servlet.

Cookies can be transient or persistent. Transient cookies last until the browser is closed, while persistent cookies are stored by the browser on the physical disk, to be retrieved and used when the same URL is accessed by the user again. Cookies, transient or persistent, have a time limit and expire after the time limit is exceeded.

Cookies are one of the simplest and most widely used techniques for session handling. They are supported by WebLogic Server as well as all client browsers and the Servlet API.

A primary limitation of cookies is the length of data that can be stored. A maximum of 4KB of data can be stored in a cookie. This limits the amount of session data that can be stored for a user.

Browsers allow disabling of cookies. If cookie acceptance is disabled, this technique is not going to work.

Tip

If the cookie-accepting feature in the browser is disabled, the WebLogic Server detects this and automatically switches the session-handling mechanism to retrieving the session identifier from an encoded URL as long as your servlet uses the encodeURL() method for generating all URLs in the response page.


Sample Program

Now you can look at a sample program (Listing 3.3) that implements this session-handling technique. Figure 3.16 illustrates the sequence diagram for the program.

Listing 3.3 BookShoppingServlet.java
 /******************************************************************************   * Class Name:BookShoppingServlet   * Extends:HttpServlet   * Description:Shopping Cart Application Using cookies,   * @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 BookShoppingServlet extends HttpServlet { //defining global variables to be used in this servlet     Book book1;     Book book2;      Book book3;     PrintWriter out;     private static final int DEFAULT_ZERO_VALUE = 0;     private static final String EXAMPLE_TYPE = "Shopping Cart Using Cookies";     ... //Method corresponding to post request of HTML, & called by doGet() method     //calls the doSessionUsingCookie method internally.     public void doPost(HttpServletRequest req, HttpServletResponse res)             throws ServletException, IOException{         res.setContentType("text/html");         out = res.getWriter();         writeHeaderZone(out , EXAMPLE_TYPE);         doSessionUsingCookie(out, req, res);         writeFooterZone(out);     }//end of doPost //Method called by doPost     public void doSessionUsingCookie(PrintWriter outputObject,             HttpServletRequest req, HttpServletResponse res){         Hashtable shoppingCartHash = null;         Cookie bookCookie = null;         Cookie[] cookies = req.getCookies();         if (cookies==null)         {             bookCookie = new Cookie(book1.getBookId(),                     Integer.toString(DEFAULT_ZERO_VALUE));             bookCookie.setMaxAge(Integer.MAX_VALUE);             res.addCookie(bookCookie);             bookCookie = new Cookie(book2.getBookId(),                     Integer.toString(DEFAULT_ZERO_VALUE));             bookCookie.setMaxAge(Integer.MAX_VALUE);             res.addCookie(bookCookie);             bookCookie = new Cookie(book3.getBookId(),                     Integer.toString(DEFAULT_ZERO_VALUE));             bookCookie.setMaxAge(Integer.MAX_VALUE);             res.addCookie(bookCookie);         }         String clickedButton = (req.getParameter("buttonName") == null)?"":req.getParameter("buttonName");         if(clickedButton.equals("view"))         {             outputObject.println("<FORM name=\"viewcart\"                     action=\"/ShoppingApp/BookShoppingServlet\"                     method=\"get\">");             outputObject.println("<B><font face = \"Verdana\"                     color=\"blue\" size=-2><p align = \"right\">Shopping Cart                     using Cookies</p></font></B>");             int book1Qty = Utility.getDefaultValue(getCookieValue(cookies, book1.getBookId()),         DEFAULT_ZERO_VALUE);             int book2Qty = Utility.getDefaultValue(getCookieValue(cookies,                     book2.getBookId()),DEFAULT_ZERO_VALUE);             int book3Qty = Utility.getDefaultValue(getCookieValue(cookies,                     book3.getBookId()),DEFAULT_ZERO_VALUE);             writeViewCartZone(outputObject, book1Qty, book2Qty, book3Qty);             outputObject.println("<p align =\"center\"><INPUT type=\"submit\"                     name=\"buttonName\" value=\"Empty Shopping Cart\"></p>");             outputObject.println("</FORM>");         }         else if(clickedButton.equals("add") || clickedButton.equals(""))         {             updateCookie(req, res, cookies,outputObject);             outputObject.println("<FORM name=\"addcart\"                     action=\"/ShoppingApp/BookShoppingServlet\"                    method=\"post\">");             outputObject.println("<B><font face = \"Verdana\" color=\"blue\"                     size=-2><p align = \"right\">Shopping Cart using                     Cookies</p></font></B>");             writeBookListZone(outputObject);             outputObject.println("<CENTER><TABLE width = 100%><TR>");             outputObject.println("<TD align = \"center\"><INPUT type=\"submit\"                     name=\"buttonName\" value=\"add\"></TD>");             outputObject.println("<TD align = \"center\"><INPUT type=\"submit\"                     name=\"buttonName\" value=\"view\"></TD>");             outputObject.println("</TR></TABLE></CENTER>");             outputObject.println("</FORM>");         }         else if(clickedButton.equals("Empty Shopping Cart")){             //setting the cookie values to null and invalidating the cookies             weblogic.servlet.security.ServletAuthentication.invalidateAll(req);             weblogic.servlet.security.ServletAuthentication.killCookie(req);             Cookie updateBookCookie = null;             updateBookCookie = new Cookie(book1.getBookId(),                     Integer.toString(DEFAULT_ZERO_VALUE));             updateBookCookie.setMaxAge(Integer.MAX_VALUE);             res.addCookie(updateBookCookie);             updateBookCookie = new Cookie(book2.getBookId(),                     Integer.toString(DEFAULT_ZERO_VALUE));             updateBookCookie.setMaxAge(Integer.MAX_VALUE);             res.addCookie(updateBookCookie);             updateBookCookie = new Cookie(book3.getBookId(),                     Integer.toString(DEFAULT_ZERO_VALUE));             updateBookCookie.setMaxAge(Integer.MAX_VALUE);             res.addCookie(updateBookCookie);             outputObject.println("<FORM name=\"addcart\"                     action=\"/ShoppingApp/BookShoppingServlet\"                     method=\"post\">");             outputObject.println("<B><font face = \"Verdana\" color=\"blue\"                     size=-2><p align = \"right\">Shopping Cart using Hidden                     Variables</p>                     </font></B>");             writeBookListZone(outputObject);             outputObject.println("<CENTER><TABLE width = 100%><TR>");             outputObject.println("<TD align = \"center\"><INPUT type=\"submit\"                     name=\"buttonName\" value=\"add\"></TD>");             outputObject.println("<TD align = \"center\"><INPUT type=\"submit\"                     name=\"buttonName\" value=\"view\"></TD>");             outputObject.println("</TR></TABLE></CENTER>");             outputObject.println("</FORM>");         }     }     public void updateCookie(HttpServletRequest req, HttpServletResponse res,             Cookie[] bookCookies, PrintWriter outputObject){         Cookie bookCookie = null;         int Book1Qty = Utility.getDefaultValue(getCookieValue(bookCookies,                 book1.getBookId()),DEFAULT_ZERO_VALUE)+                 Utility.getDefaultValue(req.getParameter("book1_qty"),                 DEFAULT_ZERO_VALUE);         int Book2Qty = Utility.getDefaultValue(getCookieValue(bookCookies,                 book2.getBookId()),DEFAULT_ZERO_VALUE)+                 Utility.getDefaultValue(req.getParameter("book2_qty"),                 DEFAULT_ZERO_VALUE);         int Book3Qty = Utility.getDefaultValue(getCookieValue(bookCookies,                 book3.getBookId()),DEFAULT_ZERO_VALUE)+                 Utility.getDefaultValue(req.getParameter("book3_qty"),                 DEFAULT_ZERO_VALUE);         bookCookie = new Cookie(book1.getBookId(), Integer.toString(Book1Qty));         bookCookie.setMaxAge(Integer.MAX_VALUE);         res.addCookie(bookCookie);         bookCookie = new Cookie(book2.getBookId(), Integer.toString(Book2Qty));         bookCookie.setMaxAge(Integer.MAX_VALUE);         res.addCookie(bookCookie);         bookCookie = new Cookie(book3.getBookId(), Integer.toString(Book3Qty));         bookCookie.setMaxAge(Integer.MAX_VALUE);         res.addCookie(bookCookie);     }     public String getCookieValue(Cookie[] bookCookies, String cookieName){         for(int i=0; i<bookCookies.length; i++)         {             if((bookCookies[i].getName()).equals(cookieName))             {                 return bookCookies[i].getValue();             }         }         return null;     }     ... }//end of BookShoppingServlet 
Figure 3.16. Sequence diagram for session handling using cookies.

graphics/03fig16.gif

The only difference between the code in Listing 3.3 and Listing 3.2 is the addition of the doSessionUsingCookie() method, which performs the session handling for the servlet. This method is called from the doPost() method.

The doSessionUsingCookie() method uses the Cookie class of the Servlet API to store and manipulate the session cookie. The cookie is a part of the HttpServletRequest and is retrieved by calling the getCookies() method of the HttpServletRequest object. This method returns an array of Cookie objects.

To determine whether a session exists between the servlet and the browser, the servlet checks whether the Cookie array retrieved is null. If it is null, the servlet concludes that no cookies exist between the browser and the servlet and hence creates a new session between them. The session in this case is the contents of the shopping cart. The servlet creates a new cookie for each of the books in your store by constructing a new cookie object, which takes a cookie identifier and empty shopping cart data as parameters. This is done in the line

 bookCookie = new Cookie(book1.getBookId(), Integer.toString(DEFAULT_ZERO_VALUE));  

The next call is to set the expiry limit of the cookie. Your cookie will be alive for a long time because the sample program sets the expiry limit to the largest integer using the setMaxAge() call:

 bookCookie.setMaxAge(Integer.MAX_VALUE);  

Finally, the browser cookie is set by calling the addCookie() method on the response object:

 res.addCookie(bookCookie);  

Repeat the same steps for the other books in your store.

To determine whether the user action is Add To Cart or View Cart, retrieve the value of the buttonName parameter from the request. This is similar to what you did for the previous session-handling techniques.

For the Add To Cart function, you need to retrieve the contents of the shopping cart as well as the new user selections. This is done by calling the updateCookie() method.

To retrieve contents of the shopping cart, you will write a method getCookieValue() that takes the array of Cookie objects and the name of the cookie whose value needs to be retrieved. The getCookieValue() method iterates through the array of Cookie objects and retrieves the value of the cookie by comparing the names of the cookies in the array with the name of the cookie you are interested in:

 if((bookCookies[i].getName()).equals(cookieName))  {     ... } 

Once you have a match, extract the value from the cookie object by calling the getValue() method on the Cookie object:

 return bookCookies[i].getValue();  

Once you have retrieved the cookie values, which are the shopping cart contents for each book, retrieve the user selections for each book and update your shopping cart cookie with the updated values for each book.

The following line sums the existing contents of the shopping cart in the cookie for book1 and the new user selection retrieved from the getParameter("book1_qty") call:

 int Book1Qty = Utility.getDefaultValue(getCookieValue(bookCookies,          book1.getBookId()),DEFAULT_ZERO_VALUE)+         Utility.getDefaultValue(req.getParameter("book1_qty"),         DEFAULT_ZERO_VALUE); 

Even though the call seems complex, it is actually very simple when you know the business logic! The getDefaultValue() utility method performs the conversion from String data to a primitive int data type, as you saw earlier in the explanation for the Utility class. Similar calculations are done for the other books in your store.

Finally, you set the updated shopping cart data in the user's browser by calling the addCookie() method on the response object after creating a new cookie with the updated values. Then send the book-listing page back to the browser.

For the View Cart function, you need to retrieve the contents of the shopping cart stored in the browser. This is done by the call

 int book1Qty = Utility.getDefaultValue(getCookieValue(cookies,           book1.getBookId()),DEFAULT_ZERO_VALUE); 

This is similar to the retrieval of shopping contents for the Add To Cart function. The only difference is that there will be no new user selections and hence no updates required to the cookie. You will perform similar actions for the rest of the books in your store.

Finally, you will generate the View Cart page using the writeViewCartZone() method with the retrieved shopping cart data as parameters.

Functionality to enable the user to empty the shopping cart is provided in the servlet. The emptying function is kicked off when the user clicks on the Back To Cart button. Since this session-handling technique is based on cookies, you need to destroy the cookies that were created for the user in this session. In addition, you also need to destroy the session that was created between the WebLogic Server and the browser application. This ensures that the entire session is wiped out. This is done by the call

 weblogic.servlet.security.ServletAuthentication.invalidateAll(req);  

The invalidateAll() call destroys the entire authentication session between the browser and the WebLogic Server.

Compile the Program

Since you are not adding any new classes nor are you changing the deployment location of the application, the compiling of the servlet program is similar to compiling the hidden-variables session-handling method.

Deploy the Program

There are no settings to be made in the deployment descriptor file for deploying the servlet using the cookie session-handling technique since this session handling is performed programmatically.

Tip

If your servlet is invoked from http and https (secure HTTP) requests, the servlet treats these requests within a session as different session requests since the ports used for sending the requests are different (port 80 for http and port 443 for https). To avoid this problem, WebLogic Server provides a setting that can be changed in the WebLogic Server specific deployment descriptor file weblogic.xml. In this file, add the following deployment descriptor:

 <session-descriptor>      <session-param>         <param-name>CookieDomain</param-name>         <param-value>yourdomain.com</param-value>     </session-param> </session-descriptor> 

where the value yourdomain.com is the domain name of your Web site. For example, for the www.samspublishing.com Web site, this would be samspublishing.com.


Execute the Program

The book-listing page is invoked from the browser by calling the following URL:

http://localhost:7001/ShoppingApp/BookShoppingServlet



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