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
* Whether the browser is restarted ).
* <P>
* Taken from Core Servlets and assumerver Pages
* From Prentice Hall and Sun Microsystems Press,
* Http://www.coreservlets.com /.
*©2000 Marty Hall; may be freely used or adapted.
*/
Public class SetCookies 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 title = "Setting Cookies ";
Out. println
(ServletUtilities. headWithTitle (title) +
"<Body bgcolor = \" # FDF5E6 \ "> \ n" +
"<H1 ALIGN = \" CENTER \ ">" + title + "</H1> \ n" +
"There are six cookies associated with this page. \ n" +
"To see them, visit the \ n" +
"<A href = \"/servlet/coreservlets. ShowCookies \ "> \ n" +
"<CODE> ShowCookies </CODE> servlet </A>. \ n" +
"<P> \ n" +
"Three of the cookies are associated only with the \ n" +
"Current session, while three are persistent. \ n" +
"Quit the browser, restart, and return to the \ n" +
"<CODE> ShowCookies </CODE> servlet to verify that \ n" +
"The three long-lived ones persist extends SS sessions. \ n" +
"</BODY> </HTML> ");
}
}