Launch your tech mastery with us—your coding journey starts now!
Course Content
Advanced Java
Cookies in Session Tracking

Cookie is a mechanism to maintain the state of an user. Before cookie, let’s see what is sesion tracking and what are ways to perform session tracking.

Session Tracking

Session simply means a particular interval of time.

Session Tracking is a way to maintain state of an user. Http protocol is a stateless protocol. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.

Why use Session Tracking?

To recognize the user.

Session Tracking Techniques

There are four techniques used in Session tracking:

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

1) Cookies

A cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

javax.servlet.http.Cookie class provides the functionality of using cookies.

Constructor of Cookie class

Cookie(String name, String value): Constructs a cookie with a specified name and value.

Commonly used methods of Cookie class

There are given some commonly used methods of the Cookie class.

  1. public void setMaxAge(int expiry):Sets the maximum age of the cookie in seconds.
  2. public String getName():Returns the name of the cookie. The name cannot be changed after creation.
  3. public String getValue():Returns the value of the cookie.
  4. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
  5. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.
 
Advantage of Cookies
  1. Simplest technique of maintaining the state.
  2. Cookies are maintained at client side.
Disadvantage of Cookies
  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in Cookie object.

Example of using Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. 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 the different value.

index.html

<form action=”FirstServlet” method=”post”>

Name:<input type=”text” name=”userName”/><br/>

<input type=”submit” value=”go”/></form>

FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class FirstServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response){  

try{

 

response.setContentType(“text/html”);  

    PrintWriter out = response.getWriter();  

 

    String n=request.getParameter(“userName”);  

out.print(“Welcome “+n);  

 

    Cookie ck=new Cookie(“uname”,n);//creating cookie object  

response.addCookie(ck);//adding cookie in the response  

 

    //creating submit button  

out.print(“<form action=’ SecondServlet’>”);  

out.print(“<input type=’submit’ value=’go’>”);  

out.print(“</form>”);  

out.close();    

}catch(Exception e){System.out.println(e);}  

  }  }  

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class SecondServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response){  

try{

response.setContentType(“text/html”);  

    PrintWriter out = response.getWriter();  

 

    Cookie ck[]=request.getCookies();  

out.print(“Hello “+ck[0].getValue());  

out.close();  

}catch(Exception e){System.out.println(e);}  

    }   }  

2)Hidden Form Field

In case of Hidden Form Field an invisible textfield is used for maintaing the state of an user. In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don’t want to depend on the browser.

Advantage of Hidden Form Field
  1. It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
  1. It is maintained at server side.
  2. Extra form submission is required on each pages.
  3. Only textual information can be used.
Example of using Hidden Form Field

In this example, we are storing the name of the user in a hidden textfield and getting that value from another servlet.

 

index.html

<form action=”FirstServlet”>

Name:<input type=”text” name=”userName”/><br/>

<input type=”submit” value=”go”/></form>

 

FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class FirstServlet extends HttpServlet {  

 

public void doGet(HttpServletRequest request, HttpServletResponse response){  

try{

 

response.setContentType(“text/html”);  

        PrintWriter out = response.getWriter();  

 

        String n=request.getParameter(“userName”);  

out.print(“Welcome “+n);  

 

        //creating form that have invisible textfield  

out.print(“<form action=’SecondServlet’>”);  

out.print(“<input type=’hidden’ name=”uname” value=’”+n+”‘>”);  

out.print(“<input type=’submit’ value=’go’>”);  

out.print(“</form>”);  

out.close();   

}catch(Exception e){System.out.println(e);}  

    }  }  

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class SecondServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

try{

 

response.setContentType(“text/html”);  

        PrintWriter out = response.getWriter();  

 

        //Getting the value from the hidden field  

        String n=request.getParameter(“uname”);  

out.print(“Hello “+n);  

out.close();  

}catch(Exception e){System.out.println(e);}  

    }  

}  

 

3)URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting
  1. It will always work whether cookie is disabled or not (browser independent).
  2. Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
  1. It will work only with links.
  2. It can send Only textual information.
Example of using URL Rewriting

In this example, we are maintaning the state of the user using link. For this purpose, we are appending the name of the user in the query string and getting the value from the query string in another page.

index.html

<form action=”FirsrServlet”>

Name:<input type=”text” name=”userName”/><br/>

<input type=”submit” value=”go”/></form>

FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class FirstServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response){  

try{

 

response.setContentType(“text/html”);  

        PrintWriter out = response.getWriter();  

 

        String n=request.getParameter(“userName”);  

out.print(“Welcome “+n);  

 

        //appending the username in the query string  

out.print(“<a href=’SecondServlet?uname=”+n+”‘>visit</a>”);  

 

out.close();  

}catch(Exception e){System.out.println(e);}  

    }  }  

 

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class SecondServlet extends HttpServlet {  

 

public void doGet(HttpServletRequest request, HttpServletResponse response)  

try{

 

response.setContentType(“text/html”);  

        PrintWriter out = response.getWriter();  

 

        //getting value from the query string  

        String n=request.getParameter(“uname”);  

out.print(“Hello “+n);  

out.close();  

 

}catch(Exception e){System.out.println(e);}  

    }  }  

4) HttpSession interface

In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks:

  1. bind objects
  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.