JSP Cookies Handling with Examples

Placement-ready Online Courses: Your Passport to Excellence - Start Now

This article discusses the cookies handling in JSP in detail. It discusses cookies, its types, working, structure. It also provides a description of setting the cookie, reading the cookies and deleting the cookies in JSP. So let’s start our journey of Cookies handling in JSP.

Cookies Handling in JSP

JSP Cookies Handling

Cookies are textual content or information stored by the server on the client side. They are mainly used to recognize a user on the web server.

Cookies are sent from server to the client (browser). Client’s local machine contains this piece of information called Cookies. Further, all these cookies(in their domain) are sent to the server for all the subsequent requests made by the client so that the server can either identify a user or can use it for other purposes like tracking etc.

Clients can flush cookies or they expire when they reach their maximum age. Some methods discussed below can define its domains.

Types of Cookies in JSP

There are basically two types of cookies:
1. Persistent cookies: These cookies are also known as permanent cookies. They remain on the hard drive and persist until the user deletes them or they expire themselves.
2. Session cookies: These cookies are also known as temporary cookies. They get deleted themselves as soon as the session ends or the browser closes.

Working of JSP Cookies(Uses)

  • A cookie can be used to remember the username and password for any site.
  • A cookie can be used for Session management. The server may store a session id on the client side. When the method getSession() is called then this session ID can be sent by the client to the server to identify it.
  • Session management using cookies fails for the users that keep their cookies blocked as no information can be saved on the client’s side.
  • A cookie can be used to remember the preference of the user.
  • We can use the method isRequestSessionIdFromCookie to see if the cookies are being used or not. If this method returns true then the cookies are being used otherwise not.

Structure of Cookies in JSP

A cookie sent by a JSP page in HTTP header looks like this:

HTTP/1.1 200 OK
Date: Sat, 25 Apr 2020 21:03:38 GMT
Server: Apache/9.0.34 (WINDOWS) PHP/4.0b3
Set-Cookie: name = my_name; expires = Sun, 26-Apr-20 21:03:38 GMT;
   path = //; domain = identify.com
Connection: close
Content-Type: text/html

A cookie saved in the browser may look like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Windows 10-15apmac ppc)
Host: localhost.demon.co.in:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en_IN
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = my_name

Cookie Class

javax.servlet.http.Cookie class provides constructors and methods to extend the functionality of cookies in a JSP code.

Constructor for Cookies

Constructor availableDescription
Cookie()It is a constructor that will construct a cookie.
Cookie(String name, String value)It is a constructor that will construct a cookie with mentioned name and value.

JSP Cookies Methods

JSP supports HTTP cookies. It does this using the servlet technology. Following are the methods used while working with the cookies in JSP.

S.No.MethodDescription
1public void setDomain(String pattern)This method defines the domain of the cookies. For e.g. a particular cookie for a respective site.
2public String getDomain()

 

This method gets the domain of the cookie.
3public void setMaxAge(int expiry)

 

This method will set the time for which cookie will remain. The expiry time is in seconds. If nothing is set, then it expires as the session ends.
4public int getMaxAge()

 

This method will get the age of the cookie in seconds. If the age is not set, then it sends -1 that shows the cookie will expire when the browser closes.
5public String getName()

 

This method will return or get the name of the cookie. A cookie’s name can’t change once it is set.
6public void setValue(String newValue)

 

This method will set the value of the cookie.
7public String getValue()This method will get the value of the cookie.
8public void setPath(String uri)

 

This method will set the path of the cookie i.e. the path it will get applied to. If undefined, the cookie gets applied to all the URLs of that directory.
9public String getPath()

 

This method will get the path of the associated cookie.
10public void setSecure(boolean flag)

 

This method tells whether the cookie needs to be sent over encrypted connections or not.
11public void setComment(String purpose)

 

This method gives a purposeful message to a cookie so that the user can understand the use of it.
12public String getComment()

 

This method returns the message of the cookie or null if it is not there,

Cookies Handling in JSP through Set, read and Delete Cookies

Now that we have discussed the basics and methods of cookies along with a description, let’s set, read, and delete cookies in JSP.

1. Setting cookies in JSP

Setting a cookie in JSP involves three important steps. These steps are

a. Creating an object of Cookie type

In this step we call a constructor i.e. Cookie. Create an object that will take the values. Pass two string values in this constructor that will be the key and cookie value. Syntax is as follows:

Cookie cookie = new Cookie(“key”, “value”)

E.g. Cookie name = new Cookie(“my_name”, request.getParameter(“my_name”));
A cookie object and its value follows some naming conventions. They should not contain symbols like [ ] ( ) = , ” / ? @ : ; and white spaces.

b. Set the age of cookie

Age of a cookie, as the name suggests, how long a cookie should survive. This can be set by setting the maximum age of the cookie. Age of a cookie is set in seconds. Syntax is as follows:

cookie.setMaxAge(seconds)

E.g. name.setMaxAge(60*60*24) (Max age of cookie is 24 hours in this example)

c. Pass it as a response in HTTP header

The third and final step to set a cookie is by adding it to the HTTP response headers. Syntax is:

response.addCookie(cookie);

E.g. response.addCookie(name);

A detailed example with explanation has been shown below to set a cookie following all the above steps: The code below is for setting the cookies.

one.jsp
<%
   // Creating cookies for name and age.  	
   Cookie name = new Cookie("User_name", request.getParameter("User_name"));
   Cookie age = new Cookie("Age", request.getParameter("Age"));
   Cookie gender = new Cookie("Gender", request.getParameter("Gender"));
  
   // Setting expiry date
   name.setMaxAge(60*60*24);
   age.setMaxAge(60*60*24);
   gender.setMaxAge(60*60*24);
  
   // Add both the cookies in the response header.
   response.addCookie( name );
   response.addCookie( age );
   response.addCookie( gender );
%>
 
<html>
   <head>
  	<title>Set Cookies</title>
   </head>
  
   <body>
               	<h2>--DataFlair--<h2>
     	<h2>Here we are setting Cookies</h2>
  	
  	<ul>
         <li><p><b>User Name:</b>
        	<%= request.getParameter("User_name")%>
     	</p></li>
         <li><p><b>Age:</b>
        	<%= request.getParameter("Age")%>
     	</p></li>
               	 <li><p><b>Gender:</b>
                         	<%=request.getParameter("Gender")%>
               	 </p></li>
  	</ul>
  
   </body>
</html>

The above code will set the cookie: creating specified objects, setting their max ages and adding them to HTTP header response. Now we will make a simple form to get the values using the code below:

<html>
   <body>
  	
  	<form action = "one.jsp" method = "GET">
     	User Name: <br/><input type = "text" name = "User_name">
     	<br />
     	Age: <br/><input type = "text" name = "Age" />
     	<br/>
               	 Gender:</br><input type = "text" name = "Gender">
               	 <br/>
               	 <input type = "submit" value = "Go" />
  	</form>
  	
   </body>
</html>

Save the file in the ROOT directory of apache tomcat. First run the file hello.jsp. It will give the following output:

set cookies in jsp

Fill the details asked and click on the go button. Then you will get the following output as the one.jsp file runs.

setting jsp cookies

Thus we have set the cookies successfully.

2. Reading cookies in JSP

Reading the set cookies is a simple process. We need to create an object of Cookie type and an array of Cookie type. Then we will get all the cookies in this array using the request.getCookie() method of HttpServletRequest. We then apply if loop and get the name and value of these cookies using the method getName() and getValue()

For Example:

two.jsp
<html>
   <head>
  	<title>Read Cookies</title>
   </head>
  
   <body>
  	
     	<h1>Reading Cookies that we set</h1>
 	
  	<%
     	Cookie my_cookie = null;
     	Cookie[] my_cookies = null;
     	
     	// Get an array of Cookies associated with the this domain
     	my_cookies = request.getCookies();
     	
     	if( my_cookies != null ) {
        	out.println("<h2> Found Cookies Name and Value</h2>");
        	
        	for (int i = 0; i < my_cookies.length; i++) {
           	my_cookie = my_cookies[i];
           	out.print("Name : " + my_cookie.getName( ) + ",  ");
           	out.print("Value: " + my_cookie.getValue( )+" <br/>");
        	}
     	} else {
        	out.println("<h2>No cookies founds</h2>");
     	}
  	%>
   </body>  
</html>

Running this code, we get the values of cookies we read. We get the following output.

reading set cookies in jsp

3. Deleting cookies in JSP

Now, while deleting the cookies in JSP, we follow similar steps to what we did in setting the cookies. We firstly read an already set cookie and then store it in an object of cookie type. Then we set the age of the cookie as zero in order to delete the cookie using the method setMaxAge(0) method. Then we add it to the Http Response Header so as to delete this cookie.

For Example:

three.jsp
<html>
   <head>
  	<title>Delete Cookies</title>
   </head>
  
   <body>
  	<center>
     	<h1>Delete Cookies</h1>
  	</center>
  	<%
     	Cookie my_cookie = null;
     	Cookie[] my_cookies = null;
     	
     	// Get an array of Cookies associated with the this domain
     	my_cookies = request.getCookies();
     	
     	if( my_cookies != null ) {
        	out.println("<h3> Found some Cookie Name and Value</h3>");
        	
    	    for (int i = 0; i < my_cookies.length; i++)
                         	{
           	my_cookie = my_cookies[i];
           	
           	//Deleting all the cookies
              	my_cookie.setMaxAge(0);
                  response.addCookie(my_cookie);
       	       out.print("Deleted cookie: " +
              	my_cookie.getName( ) + "<br/>");
           	}
           	out.print("Name : " + my_cookie.getName( ) + ",  ");
           	out.print("Value: " + my_cookie.getValue( )+" <br/>");
       	 }
      	else {
        	out.println(
        	"<h2>No cookies were founds</h2>");
     	}
  	%>
   </body>
  
</html>

In this example, we deleted all the cookies that we set and read in the previous JSP programs. You can directly delete cookies in Internet explorer by clicking on the tools button, go to Internet settings and delete browsing history that involves cookies too. Below is the output of the code.

deleting cookies in jsp

Example of JSP Cookies

Using the above code of hello.jsp, one.jsp and two.jsp we can view the values set for the cookies. In this example we have joined the setting and reading code(one.jsp and two.jsp) by adding a link of two.jsp in one.jsp. Below is the code and its output.

one.jsp
<%
   // Creating cookies for name and age.  	
   Cookie name = new Cookie("User_name", request.getParameter("User_name"));
   Cookie age = new Cookie("Age", request.getParameter("Age"));
   Cookie gender = new Cookie("Gender", request.getParameter("Gender"));
  
   // Setting expiry date
   name.setMaxAge(60*60*24);
   age.setMaxAge(60*60*24);
   gender.setMaxAge(60*60*24);
  
   // Add both the cookies in the response header.
   response.addCookie( name );
   response.addCookie( age );
   response.addCookie( gender );
%>
<html>
   <head>
  	<title>Set Cookies</title>
   </head>
   <body>
  <h2>--DataFlair--<h2>
     	<h2>Here we are setting Cookies</h2>
  	
  	<ul>
     	<li><p><b>User Name:</b>
        	<%= request.getParameter("User_name")%>
     	</p></li>
     	<li><p><b>Age:</b>
        	<%= request.getParameter("Age")%>
     	</p></li>
   <li><p><b>Gender:</b>
   <%=request.getParameter("Gender")%>
   </p></li>
  	</ul>
   <p><a href="two.jsp">Next Page will read the cookies</a><p>
   </body>
</html>

Output of above code is:

cookies handling in jsp

Advantages of using JSP Cookies

  • Cookies are saved at the client’s side by the server, thus reducing load at server side.
  • It is the easiest and most efficient way to maintain the state.
  • Cookies are the simplest way to identify a user.
  • They can be useful for Session Management as well.

Disadvantages of using Cookies in JSP

  • Cookies contain only textual information which reduces its flexibility of use.
  • If a client blocks the cookies then they will be of no use.

Conclusion

Finally we discussed cookies handling in JSP. We saw the basics of cookies, its working, structure, advantages, disadvantages etc. We discussed cookie class and methods available to support cookies in JSP etc. This article gave a detailed description about the setting, reading, deleting cookies in JSP.

Do share your feedback in the comment section if you like the article.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

The DataFlair Team is passionate about delivering top-notch tutorials and resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With expertise in the tech industry, we simplify complex topics to help learners excel. Stay updated with our latest insights.

Leave a Reply

Your email address will not be published. Required fields are marked *