by Dinesh Thakur Category: Session And Cookies

In order to read cookies that come back from the client (browser) in request header, you need to call getCookies () method of the HttpServletRequest. If the request contains no cookies this method returns null.

The following statement retrieve the cookies sent in the request header.

Cookie [] cookies = request.getCookies ();

Once you have an array of cookies, loop through the cookie array in order to retrieve information about each cookie.

The following code will retrieve the cookies sent by the client.*;



public class RetrieveCookie extends HttpServlet


      Public void doGet (HttpServletRequest request, HttpServletResponse

     response) throws ServletException, IOException


           PrintWriter out;

           //set content type and other response header files first

           response.setContentType (“text/html”);

         //write the data of the response

          out = response.getWriter ();

          //get cookie from HTTP request header

         Cookie [] cookies = request.getcookies ();

         out.println (“<HTML> <HEAD> <TITLE> Retrieving cookies </TITLE>


         out.println (“<BODY>”);         

         //check whether cookies exist

         if (cookies != null)                                             


               for (int i=0; i<cookies.length; i++ )


                   //display these cookies

                   out.println (“Cookie Name:” + cookies [i].getName ());

                   out.println (“Value:” +cookies [i].getValue ());

                   out.println (“<br>”);





               out.println (“No cookies exist”);


          out.println (“</BODY> </HTML>”);

          out.close ();



Output: Cookie Name: name Value: daljeet

              Cookie Name: email Value: This email address is being protected from spambots. You need JavaScript enabled to view it.


NOTE: When you loop through the cookie array. You might get irrelevant cookies in addition to the cookies send by you. If you want only to display the cookies send by you call getName () method on each cookie until you find one that matches with name of the cookie that you have set.

           Reading Cookies from the Client

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.