Cookies Session Tracking Mechanism

Cookies Session Tracking Mechanism in Java Servlet

In this article, I am going to discuss Cookies Session Tracking Mechanism in Java Servlet Application. Please read our previous article where we discussed Session Tracking in Java Servlet. At the end of this article, you will understand the following pointers in detail.

  1. Why Cookies?
  2. How do Cookies work?
  3. What are Cookies?
  4. What about Security?
  5. Types of Cookies
  6. Working of Cookies in Java Servlet Application
  7. How to Create, modify, Get, and delete the Cookie?
  8. Cookie Class Constructor and Methods in Java Servlet
  9. Basic Example of Cookies in Java Servlet Web Application
  10. Advantages of Cookies
  11. Disadvantages of Cookies
  12. In which area cookies are used in a web site?
  13. Java Servlet Cookies Real-Time Example: Servlet Login and Logout
Why 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 the HttpSession Session Tracking Mechanism, all the client’s conversations will be maintained at the server machine in the form of HttpSession objects. In the HttpSession Session Tracking Mechanism, if we increase the number of users then automatically the 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.

How do Cookies work?

In Cookies Session Tracking Mechanism, at each and every client, we will pick all the request parameters, prepare a separate Cookie for each and every request parameter, add all the Cookies to the response object.

In the above context, when container dispatch response to the client automatically all the added Cookies will be transferred to the client and maintain on the client machine permanently. In the above context, when we send further requests from the same client automatically all the cookies will be transferred to the server along with the request. By repeating the above process at each and every request we are able to manage the client’s previous data at the time of processing later request.

What are Cookies?

Cookies are small textual information that allocates memory at the client-side (browser window or client machine) having the capability to remember client data across multiple requests during a session. To work with cookies we need the protocol Http and the servlets of type javax.servlet.http.HttpServlet.Cookies travel over the network along with request and response.

Note: If we disable the cookies at the client browser then cookies Session Tracking Mechanism will not execute its functionality.

What about Security?

In the case of Cookies Session Tracking Mechanism, all the client’s data will be maintained at the respective client machine only, which is open to every user of that machine. So that Cookies Session Tracking Mechanism will not provide security for the application data.

Types of Cookies

There are two types of cookies:

In-memory or Session cookies or Non-Persistent Cookies: No expiry time. Allocates memory on the browser window. Once the browser window is closed, these cookies will be destroyed automatically.

Persistent Cookies: Persistent cookies allocate memory in files of client machine hard disk having a positive number as the expiry time. These cookies will not be destroyed when the browser window is closed but they will be destroyed when their expiry time is completed/ reached.

So, in simple words we can say in the case of the persistent cookie, the browser stored it in the file system of that client machine but in the case of a session cookie, the browser does not store the cookie in the user machine’s file system. As soon as the browsing session ends i.e. browser is closed, the session cookie dies.

The cookie that is created without expiration time is called an in-memory cookie. The cookie that is created with expiration time is called a persistent cookie.

Working of Cookies in Java Servlet Application

Every cookie contains a name and allows one string value. Every cookie contains a cookie ID and also remembers the web application/domain name for which it belongs to. The Server-side web resource programs of web applications create cookies and add them to the response object to send to clients. So, cookies allocate memory as String information on 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 client from server/web application along with the response, as the values of 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 special request header called “cookie”. At the client-side or browser window, we can see multiple cookies belonging to different domains.

Cookies in Java Servlet Web Application

With respect to the diagram,
  1. The form1 page gives request1 data to the FirstServlet program of CookieApp2 web application having form1/request1 data.
  2. The first servlet program executes two in-memory cookies having form1/request1 data & adds them to the response.
  3. The FirstServlet generates a response, having 2 in-memory cookies and form2 as dynamic form page these in-memory cookies become the value of set-cookies response header.
  4. The two in-memory cookies of response1 allocate memory on browser window representing form1 / request1 data and they also remember CookieApp2 as their domain name/web application name.
  5. Form2 generates request2 to the Second Servlet program of the CookieApp2 web application. This request carries form2 data and also carries the two cookie values of CookieApp2 application (form1/request1 data) as the values of RequestHeader “cookie”.
  6. SecondServlet reads form2 data directly from request2 and also reads form1/request1 data from the cookies of request2. That means the second servlet program is able to use request1/form1 data while processing request2 (which is nothing but session tracking).
  7. The second servlet program writes form1/request1 data, form2/request2 data as a record to the database table.
  8. The second servlet program generates a dynamic web page having form1/request1 data and for2/request2 data.
Cookie API (Working with methods of javax.Servlet.http.Cookie class):

Create the cookie by instantiating javax.servlet.http.Cookie classs
Cookie ck1 = new Cookie(“name”, “value”); Here, Cookie name and value must be String
res.addCookie(ck1); //ck1 acts as in-memory cookie

Cookie ck2 = new Cookie(“name”, “value”);
ck2.setMaxAge(1800); //time in the form of seconds
res.addCookie(ck2); //ck2 is persistent cookie having 1800 secs as expire time.

Send the cookie to the client
response.addCookie(ck1); //adding cookie to response object
response.addCookie(ck2); //adding cookie to response object

Note: Every cookie must be added to response.

How to modify the Cookie?

To modify cookie value:
ck1.setValue(“hyd1”);
ck2.setValue(“Navi Mumbai”);

Capturing the incoming cookie from the browser
Cookie ck[] = req.getCookies[];
if(ck!=null)
{
       for(int i=0;i<ck.length;i++)
       {
            pw.println(ck[i].getName()+””+ck[i].getValue());
       }
}

Note: cookie class has getName() and getValue() method to retrieve cookie name and value respectively

How to delete cookies?

We cannot delete cookies programmatically being from servlet programs by using API because they allocate memory at the client-side. In memory, cookies will be destroyed once the browser window is closed. Persistent cookies will be destroyed once their expiry time is reached or their related files are deleted or modified explicitly.

To know maximum age of cookies:
int time=ck1.getMaxAge(); //-1 will come which is the default max age of in-memory cookie
int time=ck2.getMaxAge(); //1800 sec will come

To know the domain name:
String s=ck1.getDomain(); //gives domain/web application name of cookie
String s2=ck2.getDomain();

Points to Remember:

A cookie is a direct concrete class. In Windows XP operating system the Internet Explorer browser window related persistent cookies allocates memory in a special text file of the following directory:
C:\Documents and Settings\<win-login user>\cookies folder
The notation of special text file is: <windows user name>@<domain/web application name>[count]
Example: admin@CookieApp1[2].txt
Here,
admin: Window username
CookieApp1: Web application name
[2]: no. of cookies
The Internet Explorer-related persistence cookie will be destroyed automatically if the end-user tries to modify content in the file where the persistent cookies reside.

In Netscape navigator browser window persistent cookies, in-memory cookies allocate memory in the browser window but persistent cookies contain expiry time. To see all the cookies, use: Tools menu -> cookie manager -> manage stored cookies

In Yahoo, Gmail websites-based login page there is a check box to remember username and password on the computer. When that checkbox is selected it uses persistence cookies to remember usernames and passwords on that computer.

Cookie Class in Java Servlet

To represent a Cookie in a web application servlet API has provided a predefined class in the form of javax.servlet.http.Cookie.

Cookie Constructor
  1. Cookie(): It helps to construct a Cookie.
  2. Cookie(String name, String value): To create a Cookie object with a particular name-value pair we have to use the following Cookie class constructor.
Cookie Methods
  1. public void addCookie(Cookie c): To add a cookie to the response object we have to use the following method from HttpServletResponse.
  2. public Cookie[] getCookies(): To get all the Cookies from the response object we need to use the following method.
  3. public String getName(): It is used to get the name of a Cookie.
  4. public String getValue(): It is used to get the value of a Cookie.
  5. public void setComment(String comment): In the web application, it is possible to provide comments to the Cookies. It is used to set the comment to Cookie.
  6. public String getComment(): It is used to get the comment from Cookie.
  7. public void setVersion(int version_no): In web applications, it is possible to provide the version number to the cookies. It is used to set a version number to Cookie.
  8. public int getVersion(): It is used to get a version number from Cookie.
  9. public void setMaxAge(int age): In web applications, it is possible to specify lifetime to the Cookies. It is used to set max-age to Cookie.
  10. public int getMaxAge(): It is used to get max age from Cookie.
  11. public void setDomain(String Domain): In web applications, it is possible to provide domain names to the Cookies. It is used to set the domain name to Cookie.
  12. public String getDomain(): It is used to get the domain name from Cookie.
  13. public void setPath(String path): In web applications, it is possible to provide a particular path to the Cookies to store. It is used to set a path to Cookie.
  14. public String getPath(): It is used to get a path from the cookie.
Basic Example of Cookies in Java Servlet Web Application

In this example, we are storing the name and password of the user in the cookie object (MyServlet1) and accessing it in another servlet (MyServlet2). As we know well that session corresponds to the particular user. So, if you access it from too many browsers with different values, you will get a different value.

index.html
<!DOCTYPE html>
<html>
<head>
 <title>Demo</title>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head>

<body>
 <form action="login"> User Name:
  <input type="text" name="userName" />
  <br/> Password:
  <input type="password" name="userPassword" />
  <br/>
  <input type="submit" value="submit" /> </form>
</body>
</html>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            response.setContentType ("text/html");
            PrintWriter pwriter = response.getWriter ();

            String name = request.getParameter ("userName");
            String password = request.getParameter ("userPassword");
            pwriter.print ("Hello " + name);
            pwriter.print ("\nYour Password is: " + password);

            //Creating two cookies
            Cookie c1 = new Cookie ("userName", name);
            Cookie c2 = new Cookie ("userPassword", password);

            //Adding the cookies to response header
            response.addCookie (c1);
            response.addCookie (c2);
            pwriter.print ("<br><a href='welcome'>View Details</a>");
            pwriter.close ();
        } 
        catch (Exception exp)
        {
        System.out.println (exp);
        }
    }   
}
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet
{
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            response.setContentType ("text/html");
            PrintWriter pwriter = response.getWriter ();

            //Reading cookies
            Cookie c[] = request.getCookies ();
            //Displaying User name value from cookie
            pwriter.print ("Name: " + c[1].getValue ());
            //Displaying user password value from cookie
            // pwriter.print("Password: "+c[2].getValue());
            pwriter.close ();
        } 
        catch (Exception exp)
        {
            System.out.println (exp);
        }
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
 <display-name>LoginExample</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <servlet>
  <servlet-name>Servlet1</servlet-name>
  <servlet-class>MyServlet1</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Servlet1</servlet-name>
  <url-pattern>/login</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>Servlet2</servlet-name>
  <servlet-class>MyServlet2</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Servlet2</servlet-name>
  <url-pattern>/welcome</url-pattern>
 </servlet-mapping>
</web-app>

Output

Cookies in Java Servlet Application

Advantages of Cookies
  1. Cookies allocate memory at the client-side which means, they do not give a burden to the server.
  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

To work with cookies our servlet type must be HttpServlet (cookies do not work with GenericServlet). Cookies can be deleted through browser settings. This may fail session tracking.

  1. In Internet Explorer: Tools menu -> internet options -> delete cookies option
  2. In Netscape: Tools menu -> cookie manager -> manage stored cookies -> remove all cookies option

Cookies can be restricted coming to clients from the server through browser settings. This may fail session tracking.

  1. In Internet Explorer: Tools menu -> internet options -> privacy tab (to block cookies)
  2. In Netscape: Tools menu -> cookie manager -> block cookies from this site to block the cookies.

The values placed in cookies can be viewed through browser settings that means there is not data secrecy. There is a restriction on the number of cookies that can be there that is per browser window, per domain maximum of 20 cookies, and all domains together per browser window maximum of 300 cookies (may vary browser to browser).

Note: Cookies can be store only string values that mean they cannot store other object java objects as values.

In which area cookies are used in a web site?

Cookies are used in the following areas of a web site

  1. To identify the user/client uniquely in a series of client-server interactions
  2. User-provided information to the website to be reused in the future by storing that information into the user machine only without the knowledge of the user.
Points to Remember:
  1. A cookie is a name-value pair of textual information exchanged between the web server and web client through the Http header.
  2. Cookies are the small textual information that allocates memory at the client-side by remembering client data across multiple requests during a session.
  3. The web resource programs of the web application create the cookies at the server-side but these cookies come to the client-side along with the response and allocate memory at the client-side.
  4. A cookie is a name-value pair of textual information exchanged between the web server and web client through the Http header.
  5. Cookies are the small textual information that allocates memory at the client-side by remembering client data across multiple requests during a session.
  6. The web resource programs of the web application create the cookies at the server-side but these cookies come to the client-side along with the response and allocate memory at the client-side.
  7. A dynamic web resource program of the web application creates the cookie and also writes to the response object so that the web server sends it to the browser (web client) along with HTTP response headers.
  8. The browser is capable of retrieving the cookie coming from the response headers and can resend the same to the web server through HTTP request headers.
  9. Netscape Incorporation Company invented a cookie mechanism and all most all the web technologies provide APIs for implementing cookie mechanisms.
  10. In the case of session tracking, session Id is exchanged between the web server and browser using this cookie mechanism only.
  11. The name of the cookie that carries session Id is “JsessionId” and the value of the cookie is container generated session Id. This is a session cookie, not a persistence cookie.
Java Servlet Cookies Real-Time Example:

Java Servlet Login and Logout Example using Cookies: In Servlet Login and Logout Example using Cookies is performed as a kind of information that is stored on the client-side. Using these links: login, logout, and profile. Users can’t go to the profile page until he/she is logged in. If the user is logged out, he needs to login again to visit the profile.

index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1" />
        <title>Servlet Login-Logout Example</title>
    </head>
    <body>
        <h1>Welcome to Login App</h1>
        <a href="login.html">Login</a>| <a href="LogoutServlet">Logout</a>|
        <a href="ProfileServlet">Profile</a>
    </body>
</html>
login.html
<form action="LoginServlet" method="post">
    Name:<input type="text" name="name" /><br />
    Password:<input type="password" name="password" /><br />
    <input type="submit" value="login" />
</form>
link.html
<a href="login.html">Login</a> | <a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr />
LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet
{
    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        request.getRequestDispatcher ("link.html").include (request, response);
        String name = request.getParameter ("name");
        String password = request.getParameter ("password");
        if (password.equals ("admin123"))
        {
         out.print ("You are successfully logged in!");
         out.print ("<br>Welcome, " + name);
         Cookie ck = new Cookie ("name", name);
         response.addCookie (ck);
        }
        else
        {
         out.print ("sorry, username or password error!");
         request.getRequestDispatcher ("login.html").include (request, response);
        }
        out.close ();
    }
}
LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet
{
    protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        request.getRequestDispatcher ("link.html").include (request, response);
        Cookie ck = new Cookie ("name", "");
        ck.setMaxAge (0);
        response.addCookie (ck);
        out.print ("you are successfully logged out!");
    }
}
ProfileServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProfileServlet extends HttpServlet
{
    protected void doGet (HttpServletRequest request,	HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        request.getRequestDispatcher ("link.html").include (request, response);
        Cookie ck[] = request.getCookies ();
        if (ck != null)
        {
         String name = ck[0].getValue ();
         if (!name.equals ("") || name != null)
         {
             out.print ("<b>Welcome to Profile</b>");
             out.print ("<br>Welcome, " + name);
         }
        }
        else
        {
         out.print ("Please login first");
         request.getRequestDispatcher ("login.html").include (request, response);
        }
        out.close ();
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation=
"http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 <servlet>
  <description></description>
  <display-name>LoginServlet</display-name>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>LoginServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LoginServlet</servlet-name>
  <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>
 <servlet>
  <description></description>
  <display-name>ProfileServlet</display-name>
  <servlet-name>ProfileServlet</servlet-name>
  <servlet-class>ProfileServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>ProfileServlet</servlet-name>
  <url-pattern>/ProfileServlet</url-pattern>
 </servlet-mapping>
 <servlet>
  <description></description>
  <display-name>LogoutServlet</display-name>
  <servlet-name>LogoutServlet</servlet-name>
  <servlet-class>LogoutServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LogoutServlet</servlet-name>
  <url-pattern>/LogoutServlet</url-pattern>
 </servlet-mapping>
</web-app>

Output

Servlet Cookies in Java

Click on “Login” to enter your credentials

Java Servlet Cookies

Press the “login” button

Servlet Cookies

Click on “Profile” to enter into Profile Page

Cookies Servlet

Click on “Logout” to logout successfully

Cookies in Servlet

In the next article, I am going to discuss Hidden Form Fields in Servlet. Here, in this article, I try to explain Cookies in Java Servlet. I hope you enjoy these Cookies in Java Servlet article.

Leave a Reply

Your email address will not be published.