jsp源码实例5(cookie)

package coreservlets;

import java.io.;
import javax.servlet.
;
import javax.servlet.http.*;

/** 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).
 1<p>   
 2* Taken from Core Servlets and JavaServer Pages   
 3* from Prentice Hall and Sun Microsystems Press,   
 4* http://www.coreservlets.com/.   
 5* © 2000 Marty Hall; may be freely used or adapted.   
 6*/   
 7  
 8public class SetCookies extends HttpServlet {   
 9public void doGet(HttpServletRequest request,   
10HttpServletResponse response)   
11throws ServletException, IOException {   
12for(int i=0; i&lt;3; i++) {   
13// Default maxAge is -1, indicating cookie   
14// applies only to current browsing session.   
15Cookie cookie = new Cookie("Session-Cookie-" + i,   
16"Cookie-Value-S" + i);   
17response.addCookie(cookie);   
18cookie = new Cookie("Persistent-Cookie-" + i,   
19"Cookie-Value-P" + i);   
20// Cookie is valid for an hour, regardless of whether   
21// user quits browser, reboots computer, or whatever.   
22cookie.setMaxAge(3600);   
23response.addCookie(cookie);   
24}   
25response.setContentType("text/html");   
26PrintWriter out = response.getWriter();   
27String title = "Setting Cookies";   
28out.println   
29(ServletUtilities.headWithTitle(title) +   
30"<body bgcolor='\"#FDF5E6\"'>\n" +   
31"<h1 align='\"CENTER\"'>" + title + "</h1>\n" +   
32"There are six cookies associated with this page.\n" +   
33"To see them, visit the\n" +   
34"<a href='\"/servlet/coreservlets.ShowCookies\"'>\n" +   
35"<code>ShowCookies</code> servlet</a>.\n" +   
36"<p>\n" +   
37"Three of the cookies are associated only with the\n" +   
38"current session, while three are persistent.\n" +   
39"Quit the browser, restart, and return to the\n" +   
40"<code>ShowCookies</code> servlet to verify that\n" +   
41"the three long-lived ones persist across sessions.\n" +   
42"</p></body>");   
43}   
44}</p>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus