8.10 Modifying Cookie Values: Tracking User Access CountsIn the previous examples, we sent a cookie to the user only on the first visit. Once the cookie had a value, we never changed it. This approach of a single cookie value is surprisingly common since cookies frequently contain nothing but unique user identifiers: all the real user data is stored in a databasethe user identifier is merely the database key. But what if you want to periodically change the value of a cookie? How do you do so?
Listing 8.6 presents a servlet that keeps track of how many times each client has visited the page. It does this by making a cookie whose name is accessCount and whose value is the actual count. To accomplish this task, the servlet needs to repeatedly replace the cookie value by resending a cookie with the identical name. Figure 8-10 shows some typical results. Listing 8.6 ClientAccessCounts.javapackage coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Servlet that prints per-client access counts. */ public class ClientAccessCounts extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String countString = CookieUtilities.getCookieValue(request, "accessCount", "1"); int count = 1; try { count = Integer.parseInt(countString); } catch(NumberFormatException nfe) { } LongLivedCookie c = new LongLivedCookie("accessCount", String.valueOf(count+1)); response.addCookie(c); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Access Count Servlet"; 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" + "<CENTER>\n" + "<H1>" + title + "</H1>\n" + "<H2>This is visit number " + count + " by this browser.</H2>\n" + "</CENTER></BODY></HTML>"); } } Figure 8-10. Users each see their own access count. Also, Internet Explorer and Netscape maintain cookies separately, so the same user sees independent access counts with the two browsers.
|