Table of contents
1.
Introduction
2.
The Basic Structure of Cookies
3.
Types of Cookies and Methods
4.
Servlet Cookie Methods
5.
Working With Cookies in JSP
5.1.
Setting Cookies with JSP
5.1.1.
Step 1: Creating a cookie object
5.1.2.
Step 2: Setting the maximum age
5.1.3.
Step 3: Sending coolie to the HTTP response headers
5.1.4.
Example
5.2.
Reading Cookies with JSP
5.2.1.
Example
5.3.
Delete Cookie with JSP
5.3.1.
Example
6.
Frequently Asked Questions
6.1.
What are cookies?
6.2.
What are cookies in Java?
6.3.
How are cookies set in JSP?
6.4.
What is the difference between cookies and sessions?
7.
Key Takeaways
Last Updated: May 4, 2024
Easy

Cookies Handling in JSP

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Cookies handling in JSP involves storing session data on the client's machine rather than the server, addressing the scalability challenges posed by HttpSession. As the number of internet users grows, storing all conversations on the server becomes impractical. 

Cookies Handling in JSP

Instead, cookies are employed to store data locally, with details passed to the server when needed.

The Basic Structure of Cookies

Cookies are nothing but just text files stored on the client's machine, and they are used for various purposes by various websites. JSP also supports HTTP cookies. JSP uses servlet technology for working with cookies.

Steps involved in Identifying and returning users:

  • Server scripts send cookies to the browser. Generally, it sends sets of cookies, For example, age, name, or any other identification number.
  • The browser stores this information for future use on the local machines.
  • And from the next time, whenever the browser sends any request to the web server, it sends those cookies to the server, and it also helps find data in the server.

The structure of the cookie:

Cookies are generally set in the HTTP header. In JSP, the headers which have cookie looks something like this:

HTTP/1.1 200 OK
Date: Tue, 18 Jan 2022 13:03:28 GMT
Server: Apache/1.3.9 (UNIX)
Set-Cookie: name = abc; expires = Tuesday, 18-Jan-22 22:03:38 GMT; 
   path = /; domain = codingninja.com
Connection: close
Content-Type: text/html

The Set-Cookie header contains a GMT date, a path, a name-value pair, and a domain, as you can see in the above example.

The value and name will be URL encoded. The expire filed instruction tells the browser to forget the cookie after a particular date and time.

The browser configured to store cookies will store the cookies until the expiry date. The browser will resend the cookie to the server when the user points it to any page that matches the domain and path of the cookie. The browser's header will look something like this:

GET / HTTP/1.0

 
User-Agent: Mozilla/4.6 (X1; I; Linux 2.2.6-15apmac ppc)
Connection: Keep-Alive


 
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = abc

With the request method, the JSP script can have access to cookies.

Types of Cookies and Methods

Broadly, there are two types of cookies:

  1. Persistent Cookie: These are the types of cookies available up to a specific time, even after closing the browser. We have to use the setMaxAge() method to get these cookies.
  2. Non-persistent cookie: This means that the data will be deleted as soon as one closes the browser. By default, we get these cookies.

Servlet Cookie Methods

S.NoMethodDescription
1Public void setDomain(string pattern)This method sets the domain to which cookies apply,
for example, codingninjas.com
2getDomain()It gets the domain of the cookie.
3setMaxAge(int expiry)It mentions and sets the time for which cookie will remain. It automatically expires after the session ends.
4getMaxAge()It returns -1 to the browser if the age of the cookie is not set. It measures the age of the cookie in seconds. It will return the name of the cookie.
5getName()It will return the name of the cookie.
6getValue()It will get the value of the cookie.
7setValue(String newValue)It will get the value of the cookie.
8setPath(string uri)It will set the path of the cookie and if it is not defined then it will get applied to all the URIs of the directory.
9getPath() It will get the path of the associated cookie.
10setComment(string purpose)It gives a message to a cookie so that the user can understand its use.
11getComment()It returns the message of the cookie and if there is no message it returns NULL.
12setSecure(Boolean flag)It tells whether the cookie needs to be sent over encrypted connections or not.


You can also read about the JSP Architecture and Lifecycle.

Working With Cookies in JSP

We can perform many functions on cookies, but here we will first set up cookies, then read cookies, and delete cookies.

Setting Cookies with JSP

Setting cookies with JSP involves three steps:

Step 1: Creating a cookie object

You can make a cookie by calling the cookie constructor with the cookie value and name, both of which are strings.

Cookie cookie = new Cookie(“Key”,” Value”);

Neither the value nor the name contains the white spaces or the following characters.

[ ] ( ) = , : @ ? ;

Step 2: Setting the maximum age

You can use the setMaxAge() function to specify the validation of the cookie. The time given is in second like below code is for 12 hours.

cookie.setMaxAge(60*60*12);

Step 3: Sending coolie to the HTTP response headers

You can use response.addCookie function to add cookies in the header of the HTTP response.

response.addCookie(cookie);

Example

Enter this code in main.JSP file:

<%
// here we are creating the cookie with the first_name
   Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
// here we are creating the cookie with the last_name
   Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
   
   // Setting the expiry date after 12 Hrs for both the cookies.
   firstName.setMaxAge(60*60*12); 
   lastName.setMaxAge(60*60*12); 
   
   
   response.addCookie( lastName );
   response.addCookie( firstName );

 
%>

 
<html>
   <head>
      <title>Setting Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Setting Cookies</h1>
      </center>
      <ul>
         <li><p><b>First Name:</b>
            <%= request.getParameter("first_name")%>
         </p></li>
         <li><p><b>Last  Name:</b>
            <%= request.getParameter("last_name")%>
         </p></li>
      </ul>
   
   </body>
</html>

Enter the following HTML code in hello.jsp file:

<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>


Check the output at http://localhost:8080/hello.jsp.The output of the above form is 

Users can enter their first and last name accordingly and then click on the submit button, and after submission, this will display the last and first name and save them as cookies. And It will pass the cookies back to the server when one clicks on submit button again.

Reading Cookies with JSP

By using the getCookies() method of HttpServletRequest user need to create an array javax.servlet.http.Cookie for reading cookies. Then cycle through the array and use getValue() and getName() to access each cookie and its associated value.

Example

Now we will read the cookies that were set up in the previous example:

<html>
   <head>
      <title>Reading Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Reading Cookies</h1>
      </center>
      <%
         Cookie cookie = null;
         Cookie[] cookies = null;
         
  
         cookies = request.getCookies();
         
         if( cookies == null ) {
   out.println("<h2>No cookies founds</h2>");
             else {
         out.println("<h2> Found Cookies Name and Value</h2>");
            //Now here we search for the cookie
            for(int j = 0; j <cookies.length; j++) {
// here we provide the value to the cookie
               cookie = cookies[j];
               out.print("Name : " + cookie.getName( ) + ",  ");
               out.print("Value: " + cookie.getValue( )+" <br/>");
            }
         }

 
         }
      %>
   </body>
   
</html>

Now put the above code in main.JSP file. Suppose if you enter first_name cookie as "Naman" and last_name cookie as "Programmer," then the output at http://localhost:8080/main.jsp will be as follows: 

Delete Cookie with JSP

Deleting a cookie is straightforward. One can delete cookies by just following the given three steps:

  • Read an already created cookie that you want to delete and store in the Cookie object.
  • Then by using the setMaxAge() method, set the age of the cookie to zero.
  • Add the cookie back to the response header.

Example

In the example below we will know how to delete an already existing cookie named last_name. 

<html>
   <head>
      <title>Reading Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Reading Cookies</h1>
      </center>
      <%
         Cookie cookie = null;
         Cookie[] cookies = null;
         
        
         cookies = request.getCookies();
         
         if( cookies != null ) {
            out.println("<h2> Found Cookies Name and Value</h2>");
            
            for (int j = 0; j < cookies.length; j++) {
               cookie = cookies[j];
               
               if((cookie.getName( )).compareTo("last_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/>");
            }
         } else {
            out.println(
            "<h2>No cookies founds</h2>");
         }
      %>
   </body>
   
</html>

Now put the above code in main.JSP file. The above file displays the following result.

Now run http://localhost:8080/main.jsp once again. It will display one cookie as follows:

Frequently Asked Questions

What are cookies?

Cookies are small files that websites store on a user's computer in order to track user behavior, customize content, and save session state.

What are cookies in Java?

Java web applications save small amounts of data on the client's computer called cookies, which help with session management and customized user experiences. 

How are cookies set in JSP?

Cookies are set in JSP by calling the addCookie() function on the HttpServletResponse object and providing the name, value, and optional parameters (path and expiration).

What is the difference between cookies and sessions?

Sessions are stored on the server; cookies are stored on the client's computer. Sessions are brief, but cookies last throughout them.

Key Takeaways

In this blog, we have learned about cookies, their need, use, types, methods for creating them, reading them, and deleting them.

If you want to know any other java framework to work on, you must refer to this article. This will give you an idea about other java frameworks and why you need to use java frameworks.

Live masterclass