A cookie is one of the most common ways to track a user on internet and maintain a user's session. Cookie is a text file using which you can store the information in user's
browser and access it when you need it. This makes cookie one of the techniques
to maintain a user's session and to differentiate a user from the others.
You can even specify the duration for which this Cookie file is going exist before it gets deleted by the browser.
Java Servlet Technology allows us to perform user's session management using its Cookie class.
Constructor of Cookie class
Constructor
Description
voidCookie(String name, String value)
Constructs a Cookie with a name and a value.
How to add a cookie
We can add cookie in the client's system by calling the addCookie() method of HttpServletResponse interface by using the response object.
Method
Description
voidaddCookie(String name, String value)
Adds a cookie within the client's browser.
Some useful methods of Cookie class.
The methods in the table below are part of javax.servlet.http.Cookie class, hence these methods are available to the object of Cookie class.
Methods
Description
voidsetDomain(String name)
Sets the domain name which will be associated with the Cookie.
StringgetDomain()
Returns the domain name associated with the Cookie.
voidsetMaxAge(int expiry)
Sets the maximum time(in seconds) till the Cookie lasts.
intgetMaxAge()
Returns the maximum time(in seconds) till the Cookie lasts.
voidsetComment(String message)
Sets a message/comment describing the Cookie.
StringgetComment()
Returns the message describing the Cookie.
voidsetValue(String value)
Sets the value of the Cookie that is already created.
StringgetValue()
Returns the value of the Cookie.
Advertisement
Creating a webpage which calls the Servlet
We are creating a webpage which asks the user to enter the name and city and press the submit button,
which when clicked calls the Servlet with the <url-pattern> SaveCookie, specified in the deployment descriptor file(web.xml),
passing this Servlet the parameters named username and cityname, using default get method.
Form1.htm
<html>
<head>
<title> Cookies Demo </title>
</head>
<body>
<b>Please enter your details :</b>
<br/>
<br/>
<form action = "SaveCookie" >
Name : <input type = "text" name = "username"/>
City : <input type = "text" name = "cityname" />
<input type = "submit" name = "submit"/>
</form>
</body>
</html>
Creating, setting the Cookie using Servlet
In this Servlet, we are going to -
create a cookie using the Cookie.
Set a cookie, by calling a method addCookie() of HttpServletResponse's response object.
Asking a user to click hyperlinks to read or delete the cookie, which was just set. Clicking on any of these hyperlinks will call the specific Servlet to read or delete the set cookie.
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String city = request.getParameter("cityname");
//Creating a Cookie object to maintain a session
Cookie cookie = new Cookie(name, city);
//Setting the cookie in the client browser
response.addCookie(cookie);
out.println("<br/>");
out.println(" Do you want to read the Cookie?");
out.println(" If yes, please visit <a href ='ReadCookie'/> Read the Cookie</a> ");
out.println("<br/>");
out.println("Do you want to delete the Cookie? if yes, please visit the <a href ='DeleteCookie'/> Delete the Cookie</a>");
}
}
This Servlet reads the cookie which was set by the first Servlet(MyServlet1.java).
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Reading Cookies</h2>");
Cookie[] array= request.getCookies();
for(int i=0; i<array.length; i++)
{
out.println("<br/>");
out.println("Name of the cookie : " + array[i].getName() + "<br/>");
out.println("Value in cookie : " + array[i].getValue());
}
}
}
This Servlet deletes the cookie which was set by the first Servlet(MyServlet1.java).
DeleteCookie.jsp
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet3 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Deleting Cookies</h2>");
Cookie[] array= request.getCookies();
for(int i=0; i<array.length; i++)
{
out.println("<br/>");
out.println("Name of the cookie : " + array[i].getName() + "<br/>");
out.println("Value in cookie : " + array[i].getValue());
//Deleting the cookie
array[i].setMaxAge(0);
response.addCookie(array[i]); //After this, although cookie will be not be visible from browser's memory
//but Cookie data will still be visible until you refresh this page.
}
}
}
Directory Structure of Servlet files
The diagram above depicts how to arrange the Servlet files in a specific directory structure, as per Java Servlet Specification-
Project Folder - We have created a project folder named CookiesEx within
the webapps folder of Tomcat installation folder. This folder contains the Servlet class(.java) file and WEB-INF folder.
WEB-INF - Within your project folder, you create another folder named WEB-INF and this folder should contain the deployment descriptor file(web.xml) of your Java Servlet program.
classes - Within the WEB-INF folder you should create a folder named classes. This folder should contain the compiled(.class) form of your Java Servlet class.
Creating the Deployment Descriptor file
As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml.
So, let's create one -
In deployment descriptor file, <servlet> has two child tags <servlet-name> and <servlet-class> :
<servlet-name> tag is used to specify a unique name for our Servlet class.
<servlet-class> tag is used to specify the full qualified name of the Servlet class .
Note
The child tag <servlet-name> of <servlet> tag is matched with the <servlet-name> child tag of
<servlet-mapping>. The
<url-pattern> child tag is used to specify the URL to access the servlet, Hence -
We have named this URL Serv1. to access the first servlet, MyServlet1.java
We have named this URL ReadCookie. to access the first servlet, MyServlet2.java
We have named this URL DeleteCookie. to access the first servlet, MyServlet3.java
Setting the classpath
Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java.
Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named
servlet-api.jar.
This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of
Tomcat installation folder.
For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib
There are two ways to set the classpath -
You could set the classpath by entering this command at the Command Prompt, but this only temporarily sets the classpath to the path of servlet-api.jar file. If you restart your system, you will have to set the classpath again.
set classpath=C:\apache-tomcat-9.0.2\lib\servlet-api.jar
In order to set the classpath permanently, you need to set your classpath system variables. A simple tutorial on how to permanently set the classpath system variables, you may read
How to permanently set the classpath system variable
Compiling the Servlet class
After setting the classpath, you need to compile the both of the Servlet class by entering the command at the folder where you've stored the Servlet class file.
javac -d WEB-INF/classes MyServlet1.java
javac -d WEB-INF/classes MyServlet2.java
javac -d WEB-INF/classes MyServlet3.java
Executing the Servlet
We are creating a webpage which asks the user to enter his/her name and city and press the submit button.
On entering the details and clicking the submit button calls the Servlet with the <url-pattern> SaveCookie, specified in the deployment descriptor file(web.xml),
passing this Servlet the parameter named username and cityname, using the default get method.
Next, on clicking Read the Cookie link calls the Second Servlet which reads the cookie and displays the value present in this Cookie.
Deleting a Cookie using JSP
We can delete an existing cookie in two steps -
First, by calling the setMaxAge() method of Cookie class and passing it a zero(0) in its parameters, which sets the cookie age
to zero seconds.
Next, by calling addCookie() method of response object deletes the cookie from the browser's memory, as shown below.
Our Servlet(MyServlet3.java) deletes the cookie which was set by the first Servlet(MyServlet1.java).
Let's go back to the same example and say - after saving the cookie, what would have happened, had we clicked the DeleteCookie hyperlink.
Next, on clicking Delete the Cookie link calls the MyServlet3 Servlet with the <url-pattern> DeleteCookie as
specified in web.xml. This Servlet deletes the cookie but the value in this cookie is displayed the first time this page loads.
Next, on refreshing the page, the values associated with the cookie are not displayed because this cookie is deleted from the browser's memory.