JSP Accessing Cookies : Read cookies in JSP



In the previous chapter we have learnt the way to set cookies using JSP. In this example we will be learning how to access the cookies using the JSP. Below tutorial will show us detail explanation about the JSP accessing cookies.

JSP Accessing Cookies :

Consider the below program –

<html>
<head>
<title>Accessing and Reading Cookies</title>
</head>
<body>
   <%
      Cookie cookie = null;
      Cookie[] cookies = null;

      cookies = request.getCookies();
      if (cookies != null) {
         out.println("<h2> List of cookies : </h2>");
         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.print("Name : " + cookie.getName() + ",  ");
            out.print("Value: " + cookie.getValue() + " <br/>");
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
   %>
</body>
</html>

Output of the Program :
reading accessing the cookies with JSP

Explanation : JSP Accessing Cookies

The above program we are accessing the cookies that are already present or valid. We need the cookie object to get the details of the cookies.

Cookie cookie = null;
Cookie[] cookies = null;

We have created the array of the cookie objects. JSP provides the way to access the cookies using the getCookies( ) method of HttpServletRequest.

cookies = request.getCookies();

Using the above line we can get all the cookies in an array. Now we can access the elements of the array using the loop to print the details of each cookie –

for (int i = 0; i < cookies.length; i++) {
   cookie = cookies[i];
   out.print("Name : " + cookie.getName());
   out.print("Value: " + cookie.getValue());
}

Now in order to print the details of each cookie we need to get individual cookie object from the array.

Method Explanation
cookie.getName() Used to print the name of the cookie
cookie.getValue() Used to print the value of the cookie