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
        {
            res.setContentType("text/html");
            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 );
         }
         out.println("</BODY></HTML>");
    }
[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]
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.