FileDocCategorySizeDatePackage
CookieServlet.javaAPI DocExample1797Thu Jun 08 14:57:04 BST 2000None

CookieServlet

public class CookieServlet extends HttpServlet
Simple Cookie-based Page Color Display servlet demo.
author
Ian Darwin
version
$Id: CookieServlet.java,v 1.1 2000/06/08 17:57:05 ian Exp $

Fields Summary
protected static final String
PREFS_BGCOLOR
The preferences cookie name
protected static final String
CUSTOMIZER
Where to go if we have not yet been customized.
protected String
faveColor
The user's chosen color, if any
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)


	     
	   

		// Go through all the cookies we have, looking for a faveColor.
		Cookie[] mySiteCookies = request.getCookies();
		for (int i=0; i<mySiteCookies.length; i++) {
			Cookie c = mySiteCookies[i];
			if (c.getName().equals(PREFS_BGCOLOR)) {
				faveColor = c.getValue();
				break;
			}
		}

		// if we did not find a faveColor in a cookie,
		// punt to customization servlet to bake one up for us.
		if (faveColor == null) {
			ServletContext sc = getServletContext();

			// Requires Servlet API 2.1 or later!
			// RequestDispatcher rd = 
			//	sc.getRequestDispatcher(CUSTOMIZER");
			//rd.forward(request, response);

			// Do it the old way
			response.sendRedirect(CUSTOMIZER);
		}

		// OK, we have a color, so we can do the page.
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");

		out.println("<html><title>A Custom-Colored Page</title>");
		out.print("<body bgcolor=\"");
		out.print(faveColor);
		out.println("\">");
		out.println("<P>Welcome! We hope you like your colored page!</P>");
		out.println("</body></html>");
		out.flush();