A Simple Cookie-Based Web Site


Let's look at a very simple web page, as shown in Figure 3-2.

Figure 3-2. Simple web page.


You'll notice a counter is displayedthe server uses a cookie to track the number of times the page has been viewed. Each time the page is refreshed, the counter is increased. For this functionality to work, we need to support cookies on the clientotherwise, the counter won't update.

The other thing you'll notice is the form, which enables a client that does support cookies to reset the counter. Let's look at the JSP code for this simple web page in Listing 3-2.

Listing 3-2. Simple Cookie JSP
 <%@ page contentType="text/html; charset=utf-8" language="java" %> <%     Cookie myCookie;     String counter = "0";     if(request.getParameter("Submit") != null)     {         myCookie = new Cookie("counter", null);         response.addCookie(myCookie);     } else {         Cookie[] cookies = request.getCookies();         if(cookies != null)             for(int i = 0; i < cookies.length; i++)             {                 if(cookies[i].getName().compareTo("counter") == 0)                counter = cookies[i].getValue();             }         if(counter == null)             counter = "0";         if(counter.compareTo("null") == 0)             counter = "0";         counter = (Integer.parseInt(counter) + 1) + "";         session.setAttribute("counter", counter);         myCookie = new Cookie("counter", counter);         response.addCookie(myCookie);     } %> <html><head><title>Cookie Test Page</title></head> <body> <p>Counter: <%= counter %></p> <form name="clear_form"  method="post" action="index.jsp">   <input type="submit" name="Submit" value="Clear Cookies!"/> </form> <p><a href="index.jsp">Reload Page</a></p> </body> </html> 

You'll notice the use of cookie management facilities built into the standard JSP/servlet functionality. It's a shame that similar functionality isn't built into the standard Java SDK for accessing resources via HTTPinstead, we must turn to the Jakarta Commons HttpClient component for assistance.



    Apache Jakarta Commons(c) Reusable Java Components
    Real World Web Services
    ISBN: N/A
    EAN: 2147483647
    Year: 2006
    Pages: 137
    Authors: Will Iverson

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