Java Reference
In-Depth Information
When a web browser requests a URL, the browser checks to see whether any cookies are
associated with that URL. If there are, the cookies are sent along with the request.
In a servlet, call the getCookies() method of an HttpServletRequest object to receive
an array of Cookie objects. You can call each cookie's getName() and getValue() meth-
ods to find out about that cookie and do something with the data.
Listing 21.2 contains ColorServlet , an extended version of the ROT-13 servlet that
enables a user to select the background color of the page. The color is stored as a cookie
called color , and the servlet requests the cookie from a web browser every time the
servlet is loaded.
LISTING 21.2
The Full Text of ColorServlet.java
1: import java.io.*;
2:
3: import javax.servlet.*;
4: import javax.servlet.http.*;
5:
6: public class ColorServlet extends HttpServlet {
7:
8: public void doPost(HttpServletRequest req, HttpServletResponse res)
9: throws ServletException, IOException {
10:
11: String pageColor;
12: String colorParameter = req.getParameter(“color”);
13: if (colorParameter != null) {
14: Cookie colorCookie = new Cookie(“color”, colorParameter);
15: colorCookie.setMaxAge(31536000);
16: res.addCookie(colorCookie);
17: pageColor = colorParameter;
18: } else {
19: pageColor = retrieveColor(req.getCookies());
20: }
21: String text = req.getParameter(“text”);
22: String translation = translate(text);
23: res.setContentType(“text/html”);
24: ServletOutputStream out = res.getOutputStream();
25: out.println(“<html>”);
26: out.println(“<body bgcolor=\”” + pageColor + “\”>”);
27: out.println(“<head><title>ROT-13 Translator</title></head>”);
28: out.println(“<h1>ROT-13 Translator</h1>”);
29: out.println(“<p>Text to translate:”);
30: out.println(“<form action=\”ColorServlet\” method=\”post\”>”);
31: out.println(“<textarea name=\”text\” ROWS=8 COLS=55>”);
32: out.println(translation);
33: out.println(“</textarea>”);
34: out.println(“<p>Background color of page:”);
Search WWH ::




Custom Search