JSP Tutorial - JSP Cookies








Cookies are text files stored on the client computer and are used to store information.

A JSP can access to the cookies through the request method request.getCookies() which returns an array of Cookie objects.

The following table lists useful methods associated with Cookie object.

MethodDescription
setDomain(String pattern)sets the domain for cookie, for example java2s.com.
String getDomain()gets the domain to which cookie applies.
setMaxAge(int seconds)Sets how much time in seconds should elapse before the cookie expires. By default, the cookie will last for the current session.
getMaxAge()Get cookie age in seconds. -1 indicating the cookie will persist until browser shutdown.
String getName()returns the name of the cookie, which cannot be changed after creation.
setValue(String newValue)sets the value associated with the cookie.
String getValue()gets the value associated with the cookie.
setPath(String uri)sets the path this cookie applies. By default, the cookie is returned for all URLs in the current directory and subdirectories.
String getPath()gets the path to which this cookie applies.
setSecure(boolean flag)sets to send cookie over encrypted (i.e. SSL) connections.
setComment(String purpose)Sets a comment that describes a cookie's purpose.
String getComment()get the comment for the cookie

The following code shows how to set cookies in JSP.

Cookie cookie = new Cookie("key","value");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);




Example

Save the following file as main.jsp. The top part of the main.jsp file is all in Java code wrapped in <% ... %>. The logic gets the first name and last name from the parameters then create a cookie and add the names to it. It sets the age for a cookie for one hour.

<%
   // Create cookies for first and last names.      
   Cookie firstName = new Cookie("first_name",request.getParameter("first_name"));
   Cookie lastName = new Cookie("last_name",request.getParameter("last_name"));

   // Set expiry date after one hour for both the cookies.
   firstName.setMaxAge(60*60); 
   lastName.setMaxAge(60*60); 

   // Add both the cookies in the response header.
   response.addCookie( firstName );
   response.addCookie( lastName );
%>
<html>
<body>
<ul>
<b>First Name:</b><%= request.getParameter("first_name")%><br/>
<b>Last  Name:</b><%= request.getParameter("last_name")%>
</body>
</html>

The following HTML page is to call the main.jsp.

<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>




Reading Cookies with JSP

To read cookies, create an array of javax.servlet.http.Cookie objects by calling the getCookies() method from HttpServletRequest.

Then loop through the array, and use getName() and getValue() methods to access each cookie and associated value.

The following code shows how to read cookies set in previous example.

<html>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   cookies = request.getCookies();
   if( cookies != null ){
      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>

Delete cookies

To delete cookies, set cookie age to zero using setMaxAge() method.

The following code shows how to delete a cookie. It only deletes the cookie named first_name

<html>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   cookies = request.getCookies();
   if( cookies != null ){
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         if((cookie.getName( )).compareTo("first_name") == 0 ){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("Deleted cookie: " + cookie.getName( ) + "<br/>");
         }
         out.print("Name : " + cookie.getName( ) + ",  ");
         out.print("Value: " + cookie.getValue( )+" <br/>");
      }
  }
%>
</body>
</html>