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).
*
* Taken from Core Servlets and JavaServer 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) +
"\n" +
"
ShowCOOKIEs
servlet.\n" + \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" +
"ShowCOOKIEs
servlet to verify that\n" +
"the three long-lived ones persist across sessions.\n" +
"");
}
}