Cookies in JSP

Cookies are text files stored on the client computer and they are kept for various information tracking purpose. JSP transparently supports HTTP cookies using underlying servlet technology.

There are three steps involved in identifying returning users:

         Server script sends a set of cookies to the browser. For example name, age, or identification number etc.

         Browser stores this information on local machine for future use.

         When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well.

Setting Cookies with JSP:

Setting cookies with JSP involves three steps:

(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the following characters:

[ ] ( ) = , " / ? @ : ;

(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:

response.addCookie(cookie);

 

 

Example:

Let us modify our Form Example to set the cookies for first and last name.

<%

// 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 24 Hrs for both the cookies.

firstName.setMaxAge(60*60*24);

lastName.setMaxAge(60*60*24);

 

// Add both the cookies in the response header.

response.addCookie( firstName );

response.addCookie( lastName );

%>

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

Let us put above code in main.jsp file and use it in the following HTML page:

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

Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/webapps/ROOT directory.

 

 

Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.

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

Example:

Let us read cookies which we have set in previous example:

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

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

Found Cookies Name and Value

Name : first_name, Value: John
Name : last_name, Value: Player

Delete Cookies with JSP:

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:

  1. Read an already exsiting cookie and store it in Cookie object.
  2. Set cookie age as zero using setMaxAge() method to delete an existing cookie.
  3. Add this cookie back into response header.

Example:

Following example would delete and existing cookie named "first_name" and when you would run main.jsp JSP next time it would return null value for first_name.

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

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/>");

}

}else{

out.println(

"<h2>No cookies founds</h2>");

}

%>

</body>

</html>

Now let us put above code in main.jsp file and try to access it. It would display the following result:

Cookies Name and Value

Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player

Now try to run http://localhost:8080/main.jsp once again and it should display only one cookie as follows:

Found Cookies Name and Value

Name : last_name, Value: Player

You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies.