How to read cookies with JSP?


To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

Let us now read cookies that were set in the previous example −

Example

 Live Demo

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

         // Get an array of Cookies associated with the this domain
         cookies = request.getCookies();

         if( cookies != null ) {
            out.println("<h2> Found Cookies Name and Value</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>

Let us now put the above code in main.jsp file and try to access it. If you set the first_name cookie as "John" and the last_name cookie as "Player" then running  http://localhost:8080/main.jsp  will display the following result −

Output

Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
raja
Published on 22-Mar-2019 05:27:30
Advertisements