How do I access a cookie from a servlet?

Richard Raszka

Cookies can be accessed from a servlet usingthe HttpRequest class and the method getCookies. Sample code is included below:

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

   public class PrintCookies extends HttpServlet
       public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
            PrintWriter out = res.getWriter();

            // Get the Cookies
            Cookie[] cookies = req.getCookies();

            out.println("<HTML><HEAD><TITLE>COOKIE Values<TITLE></HEAD>");
            out.println("<BODY><H1>Cookies in Session</H1>");
            // Process the cookies
            for (int i = 0; i <cookies.length; i++)
               String name = cookies[i].getName();
               String value = cookies[i].getValue();
               out.println("Cookie Name  ="+name);
               out.println("Cookie Value  ="+value );
[So, to be clear, if you want to access cookie "foo", replace the "out.println" statements with
if (name.equals("foo")) {
   out.println(name + " = " + value); // or whatever
Unfortunately, there's no "getCookieByName()" method. -Alex]