[ Team LiB ] Previous Section Next Section

Storing Data in a Cookie

In the Hour 6, you learned that cookies can be used to store information at the client. As you read through the examples in this hour, you may have even considered the idea of using a cookie to store the items in the shopping cart. Although this is possible, it's generally a better idea to store something that uniquely identifies the user and then use that as a key to find the items and populate a shopping cart.

You should try to avoid sending any sensitive information in a cookie if at all possible. Cookie files on the user's PC usually are not encrypted. Although someone might not be able to retrieve the cookie over the Internet, having unencrypted credit card data in a file on a PC is not very secure.

Using Cookies in Servlets and JSPs

Recall that the Cookie class represents a cookie that needs to be stored on a browser or a cookie that has been sent from the browser. When you create a new cookie, you must supply an initial name and value for the cookie. You can change the value and any of the cookie's other attributes after it has been created, but you can't change its name.

The following line of code creates a new cookie:


Cookie cook = new Cookie("UserID", "Bob");

You can use the setDomain and setPath methods in the cookie to restrict it to a specific domain and pathname. The following lines of code restrict the cookie to a domain of ".wutka.com" and a path of "/examples":


cook.setDomain(".wutka.com");
cook.setPath("/examples");

To store a cookie on the browser, just add the cookie to the response by calling response.addCookie:


response.addCookie(cook);

Remember to Set a Cookie First

graphics/bytheway_icon.gif

The cookie is sent back to the browser as part of the response header. If your JSP or servlet is not buffered, you must be very careful to send the cookie back before you write any part of the response. If you call response.flushBuffer, you cannot store any cookies after the buffer has been flushed.


Having Trouble with the Example?

graphics/bytheway_icon.gif

If you are having trouble storing or retrieving cookies, see the "Q&A" section at the end of this hour.


Listing 13.17 shows a servlet that sends a cookie to the browser.

Listing 13.17 Source Code for SaveCookieServlet.java
package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SaveCookieServlet extends HttpServlet
{
    public void service(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException
    {

        Cookie cook = new Cookie("examplesinfo", "Hello Cookie!");
        cook.setDomain(".wutka.com");
        cook.setPath("/shoppingcart");

        response.addCookie(cook);

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.println("<html><body bgcolor=\"#ffffff\">");
        out.println("Your cookie has been saved");
        out.println("</body></html>");
    }
}

To retrieve cookie values, use request.getCookies:


Cookie cookies[] = request.getCookies();

Listing 13.18 shows a servlet that retrieves all the cookies that have been sent to it and displays their contents.

Listing 13.18 Source Code for DumpCookiesServlet.java
package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class DumpCookiesServlet extends HttpServlet
{
    public void service(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException
    {
        Cookie[] cookies = request.getCookies();

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.println("<html><body bgcolor=\"#ffffff\">");

        out.println("Your browser sent the following cookies:");
        out.println("<pre>");

        if (cookies != null)
        {
            for (int i=0; i < cookies.length; i++)
            {
                out.println(cookies[i].getName()+": "+cookies[i].getValue());
            }
        }

        out.println("</pre>");
        out.println("</body></html>");
    }
    [ Team LiB ] Previous Section Next Section