8.9 Putting the Cookie Utilities into Practice

Listing 8.5 redoes the RepeatVisitor servlet of Listing 8.1. The new version ( RepeatVisitor2 ) has the same functionality as the old version: it says "Welcome Aboard" to first-time visitors and "Welcome Back" to repeat visitors . However, it uses the cookie utilities of Section 8.8 to simplify the code in two ways:

  1. Instead of calling request.getCookies and looping down that array examining each name , it merely calls CookieUtilities.getCookieValue .

  2. Instead of creating a Cookie object, calculating the number of seconds in a year, and then calling setMaxAge , it merely creates a LongLivedCookie object.

Figures 8-8 and 8-9 show the results.

Listing 8.5 RepeatVisitor2.java
 package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** A variation of the RepeatVisitor servlet that uses  *  CookieUtilities.getCookieValue and LongLivedCookie  *  to simplify the code.  */ public class RepeatVisitor2 extends HttpServlet {   public void doGet(HttpServletRequest request,                     HttpServletResponse response)       throws ServletException, IOException {     boolean newbie = true;  String value =   CookieUtilities.getCookieValue(request, "repeatVisitor2",   "no");  if (value.equals("yes")) {       newbie = false;     }     String title;     if (newbie) {  LongLivedCookie returnVisitorCookie =   new LongLivedCookie("repeatVisitor2", "yes");  response.addCookie(returnVisitorCookie);       title = "Welcome Aboard";     } else {       title = "Welcome Back";     }     response.setContentType("text/html");     PrintWriter out = response.getWriter();     String docType =       "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +       "Transitional//EN\">\n";     out.println(docType +                 "<HTML>\n" +                 "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +                 "<BODY BGCOLOR=\"#FDF5E6\">\n" +                 "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +                 "</BODY></HTML>");   } } 
Figure 8-8. First visit by a client to the RepeatVisitor2 servlet.

graphics/08fig08.jpg

Figure 8-9. Subsequent visit by a client to the RepeatVisitor2 servlet.

graphics/08fig09.jpg



Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

Similar book on Amazon

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