Cookies Handling in JSP

Cookies Handling in JSP with Examples

In this article, I am going to discuss Cookies Handling in JSP with Examples. Please read our previous article where we discussed Session Tracking in JSP. At the end of this article, you will understand the following pointers.

  1. When do we need to use Cookies?
  2. What are Cookies?
  3. How Cookie works
  4. Types of Cookie
  5. Advantage and Disadvantage of Cookies
  6. How to Handle Cookie in JSP?
  7. JSP Cookies API
  8. Servlet Cookies Methods
  9. Restricted characters in cookies
  10. How to Set or Create Cookies with JSP / Sending Cookies to Client
  11. Set Cookies Example with JSP
  12. How to Read Cookies with JSP
  13. How to Delete Cookies with JSP
  14. Delete Cookies Example with JSP
  15. Username and Password Functionality using Cookies example
When do we need to use Cookies?

A cookie is a small object; it can be used to represent a single name-value pair and which will be maintained permanently at the client machine. In HttpSession Session Tracking Mechanism, all the client’s conversations will be maintained at the server machine in the form of HttpSession objects. In HttpSession Session Tracking Mechanism, if we increase the number of users then automatically a number of HttpSession objects will be created at the server. So that HttpSession Tracking Mechanism will increase the burden to the server machine. To overcome the above problem, we have to use an alternative mechanism, where we have to manage all the client’s conversations at the respective client machines only. To achieve the above requirement, we have to use Cookies Session Tracking Mechanism.

What are Cookies?

Cookies are used to transfer the data between multiple form-based applications. Simply a cookie is a small piece of information sent by the server to any client. Every cookie will store the data in the form of key-value pair. The server will add the cookie to the response header by using the SetCookie header and send it to the client. Cookies will be stored in the browser by using the domain name of the website. The browser can contain cookies from multiple domains. The client needs to use HeaderCookie to get all the cookies available in the browser.

Types of Cookies in JSP
  1. Persistent Cookie: Persistent cookies means the cookie data will be available even though we close the browser up to a specified time. If we want to get persistent cookies we have to use the setMaxAge() method.
  2. Non-Persistent Cookie: Non-persistent cookies means the cookie data will be deleted when we close the browser immediately. By default, we get non-persistent cookies.
How do the Cookies Work in JSP?

Every cookie contains a name and allows one string value. Every cookie contains a cookie ID and also remembers the web application/domain name to which it belongs to. Server-side web resource programs of web applications create cookies and add them to the response to send to the client. So, cookies allocate memory as String information at the client-side. Cookies go back to the web application along with the request when the browser window gives a request back to the web application for which these cookies belong to. Cookies come to the client from the server/web application along with the response, as the values of the special response header called “set-cookie”. Cookies go back to the web application along with the request given by the browser window, as the values of the special request header called “cookie”. At the client-side or browser window, we can see multiple cookies belonging to different domains.

Advantages of Cookies:
  1. Compared to hidden variables cookies are better to transfer the data because once we store the cookie, we can get the data on any page of the website directly.
  2. Cookies work with all server-side technologies and all servers.
  3. Persistent cookies can remember client data even after the session having expiry time.
Disadvantages of Cookies:
  1. If the client disables the cookies in the browser we can work with cookies.
  2. For security reasons, it is not recommended to use cookies.
  3. If we want to a huge amount of data between server and client it will be complicated.
How to handle Cookie?

Handling cookie involves below three steps:

  1. Creating a cookie object
  2. Setting the maximum age of cookie
  3. Sending cookie into the HTTP response headers
JSP Cookies API

JSP provides a cookie class in javax.servlet.http package. We can call Cookie with a cookie name and a cookie value as follows:

  1. Cookie(): It will construct a cookie.
  2. Cookie(String name, String value): It will construct a cookie with mentioned name and value.
Cookies Methods
  1. setDomain(String pattern): It defines the domain of the cookie.
  2. getDomain(): It gets the domain of the cookie.
  3. setMaxAge(int expiry): It sets the time for which the cookie will remain. It expires automatically when the session ends if nothing is set.
  4. getMaxAge(): It gets the age of the cookie in seconds. It sends -1 when the browser closes if the age is not set.
  5. getName(): It will return the name of the cookie.
  6. setValue(String newValue): It will set the value of the cookie.
  7. getValue(): It will get the value of the cookie.
  8. setPath(String uri): It will set the path of the cookie. If the path is not defined, then the cookie gets applied to all the URLs of that directory.
  9. getPath(): It will get the path of the associated cookie.
  10. setSecure(Boolean flag): It tells whether the cookie needs to be sent over encrypted connections or not.
  11. setComment(String purpose): It gives a message to a cookie so that the user can understand the use of it.
  12. getComment(): It returns the message of the cookie and returns null if it is not there.
Restricted Characters in Cookie

Following is the list of restricted characters which we cannot use in name and value of a cookie.
, (comma)
= (equals)
( ) (parenthesis)
” (double quotes)
[] (square brackets)
/ (slash)
: (colon)
@

Sending Cookies to the client / How to set Cookie?
  1. Creating a cookie: Cookie cookie = new Cookie(“key”,”value”);
  2. Setting the maximum age: Cookie.setMaxAge(60*60*24);
  3. Sending the cookie into the HTTP response headers: response.addCookie(cookie);
Cookies Handling Example in JSP

In this example, we are setting the cookie. In setCookie.html we are taking a form that has to be processed in main.jsp. We are also taking two fields “First name” and “Last name” which have to be taken as input from the user with a submit button. In main.jsp we are creating two cookie objects of “First name” and “Last name” using request.getParameter. We are also adding age to both the cookies. Cookies added to the session of firstname and lastname can be fetched by getParameter().

setCookie.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Setting Cookies</title>
</head>
<body>
<h1>Setting Cookies</h1>
 <form action="main.jsp" method="GET">
  First Name: <input type="text" name="first_name"> <br /><br/> Last
  Name: <input type="text" name="last_name" /><br/><br/> <input type="submit" value="Submit" />
 </form>
</body>
</html>
main.jsp
<%
// 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>
<h1>Setting Cookies</h1>
 <ul>
  <b>First Name:</b><%=request.getParameter("first_name")%><br /><br/>
  <b>Last Name:</b><%=request.getParameter("last_name")%>
</body>
</html>
Output

Cookies Handling in JSP with Examples

Once you click on the Submit button, you will get the following output.

Cookies Handling in JSP

How to Read Cookies in JSP?

Create an array javax.servlet.http.Cookie objects by calling getCookies() method from HttpServletResponse to read the cookies. Then use getName() and getValue() methods to access each cookie and associated value using if loop.

JSP Cookies Read Example

In this example, we will create an object of Cookie type and an array of Cookie type which will get all the cookies using request.getCookie() method of HttpServletRequest. Then we will get the name and value of these cookies using the getName() and getValue() method by applying the if loop.

readCookie.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Read Cookies</title>
</head>
<body>
<h1>Read Cookies </h1>
 <%
  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>
Output

How to Read Cookies in JSP?

How to Delete Cookies?

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

Delete Cookies Example in JSP

In this example, we have set the cookie to zero to delete the cookie using the setMaxAge() method. After that add it to the HTTP Response Headers to delete this cookie.

deleteCookies.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Delete Cookies</title>
</head>
<body>
<h1>Delete Cookies</h1>
 <%
  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>
Output

Delete Cookies Example in JSP

Remember Username and Password Example in JSP

In this example, we are using cookies to remember username and password features. In the RememberMe.jsp file, we have created username and password fields with a Remember Me checkbox, which will check for a cookie. If the cookie is found it will set the value of fields with the cookie values. In the HomePage.jsp file we will display username and password. If the user has checked the “Remember Me” check box, the JSP will add a username and password as a cookie.

RemenberMe.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Form</title>
</head>
<body>
 <%
  Cookie[] cookies = request.getCookies();
 String username = "";
 String password = "";
 if (cookies != null) {
  for (int i = 0; i < cookies.length; i++) {
   Cookie cookie = cookies[i];
   if (cookie.getName().equals("username-cookie")) {
  username = cookie.getValue();
   } else if (cookie.getName().equals("password-cookie")) {
  password = cookie.getValue();
   }
  }
 }
 %>
 <form name="logonform" action="HomePage.jsp" method="POST">
  Username: <input type="text" name="username" value="<%=username%>" />
  <br /> <br/>Password:<input type="password" name="password"
   value="<%=password%>" /> <br /> <br/>Remember Me<input type="checkbox"
   name="rememberMe" value="true" /> <br/><br/><input type="submit" value="Submit" />
 </form>
</body>
</html>
HomePage.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Display Details</title>
</head>
<body>
 <%
  String username = request.getParameter("username");
 String password = request.getParameter("password");
 String message = "Username is : " + username + "<br/> Password is :" + password;
 String rememberMe = request.getParameter("rememberMe");
 if (rememberMe != null) {
  Cookie usernameCookie = new Cookie("username-cookie", username);
  Cookie passwordCookie = new Cookie("password-cookie", username);
  usernameCookie.setMaxAge(24 * 60 * 60);
  passwordCookie.setMaxAge(24 * 60 * 60);
  response.addCookie(usernameCookie);
  response.addCookie(passwordCookie);
 }
 %>
 <strong> <%=message%>
 </strong>
</body>
</html>
Output

Enter username and password and check the “Remember Me” check box and click submit. Here, HomePage.JSP page will add cookies. If you do not check the “Remember Me” check box, the cookies will not be added.

Remember Username and Password Example in JSP

You will get the following output after clicking on Submit button.

JSP Cookies Handling with Examples

In the next article, I am going to discuss JSP File Uploading and Downloading with Examples. Here, in this article, I try to explain JSP Cookies Handling with Examples. I hope you enjoy this Cookies Handling in JSP with Examples article.

Leave a Reply

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