Edit Edit

Java Servlet FAQ


How do you retrieve a cookie?


Use HttpServletRequest's getCookies() to get an array of all the cookies:

public Cookie[] getCookies()

Then, iterate through the array of Cookie objects until you find the cookie that you're looking for. The Cookie class has getName() and getValue() to get the name and value of the Cookie.

For example, if you wanted to use a cookie to show the name of a customer at a welcome page, the servlet would look like this:

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

public class Welcome extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
                      throws ServletException, IOException
    {

       // set the content type
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();

       // get the list of cookies
       Cookie[] cookies = req.getCookies();

       // walk through the list until we find the customer cookie
       int i;
       String customer_name, cookie_name;
       for (i=0; i<cookies.length; i++) {
           cookie_name = cookies[i].getName();
           if (cookie_name.Equals("CustomerName")) {
               customer_name = cookies[i].getValue();
               break;
           }
       }

       // output the welcome page
       out.println("<HTML>");
       out.println("<HEAD><TITLE>Welcome</TITLE></HEAD>");
       out.println("<BODY>");
       if (customer_name == null) {
           // customer hasn't logged in with his name yet
           out.println("Welcome");
       }
       else {
           // show the customer name that we obtained from the cookie
           out.println("Welcome back, " + customer_name);
       }
       out.println("</BODY>");
       out.println("</HTML>");
    }
}



Last updated 01/03/2000 10:39:01 PM