8.7 Differentiating Session Cookies from Persistent CookiesThis section illustrates the use of the cookie attributes by contrasting the behavior of cookies with and without a maximum age. Listing 8.2 shows the CookieTest servlet, a servlet that performs two tasks :
Figure 8-5 shows the result of the initial visit, Figure 8-6 shows a visit immediately after that, and Figure 8-7 shows the result of a visit after the user restarts the browser. Listing 8.2 CookieTest.javapackage coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Creates a table of the cookies associated with * the current page. Also sets six cookies: three * that apply only to the current session * (regardless of how long that session lasts) * and three that persist for an hour (regardless * of whether the browser is restarted). */ public class CookieTest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; String title = "Active Cookies"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Cookie Name\n" + " <TH>Cookie Value"); Cookie[] cookies = request.getCookies(); if (cookies == null) { out.println("<TR><TH COLSPAN=2>No cookies"); } else { Cookie cookie; for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println("<TR>\n" + " <TD>" + cookie.getName() + "\n" + " <TD>" + cookie.getValue()); } } out.println("</TABLE></BODY></HTML>"); } } Figure 8-5. Result of initial visit to the CookieTest servlet. This is the same result as when visiting the servlet, quitting the browser, waiting an hour, and revisiting the servlet.
Figure 8-6. Result of revisiting the CookieTest servlet within an hour of the original visit, in the same browser session (browser stayed open between the original visit and the visit shown here).
Figure 8-7. Result of revisiting the CookieTest servlet within an hour of the original visit, in a different browser session (browser was restarted between the original visit and the visit shown here).
|