packagecoreservlets;
importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
/**Setssixcookies:threethatapplyonlytothecurrent
*session(regardlessofhowlongthatsessionlasts)
*andthreethatpersistforanhour(regardlessof
*whetherthebrowserisrestarted).
*<P>
*TakenfromCoreServletsandJavaServerPages
*fromPrenticeHallandSunMicrosystemsPress,
*http://www.coreservlets.com/.
*©2000MartyHall;maybefreelyusedoradapted.
*/
publicclassSetCookiesextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)
throwsServletException,IOException{
for(inti=0;i<3;i++){
//DefaultmaxAgeis-1,indicatingcookie
//appliesonlytocurrentbrowsingsession.
Cookiecookie=newCookie("Session-Cookie-"+i,
"Cookie-Value-S"+i);
response.addCookie(cookie);
cookie=newCookie("Persistent-Cookie-"+i,
"Cookie-Value-P"+i);
//Cookieisvalidforanhour,regardlessofwhether
//userquitsbrowser,rebootscomputer,orwhatever.
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Stringtitle="SettingCookies";
out.println
(ServletUtilities.headWithTitle(title)+
"<BODYBGCOLOR="#FDF5E6">n"+
"<H1ALIGN="CENTER">"+title+"</H1>n"+
"Therearesixcookiesassociatedwiththispage.n"+
"Toseethem,visitthen"+
"<AHREF="/servlet/coreservlets.ShowCookies">n"+
"<CODE>ShowCookies</CODE>servlet</A>.n"+
"<P>n"+
"Threeofthecookiesareassociatedonlywiththen"+
"currentsession,whilethreearepersistent.n"+
"Quitthebrowser,restart,andreturntothen"+
"<CODE>ShowCookies</CODE>servlettoverifythatn"+
"thethreelong-livedonespersistacrosssessions.n"+
"</BODY></HTML>");
}
}