Java Servlet – Session Tracking Using Cookies

Spread the love

As many of you know, all the requests using HTTP protocol is stateless.

Stateless means each request is considered as the new request. So it means that the user state is not maintained.  So we need to maintain the state of an user to recognize to a particular user.

This concept is known as Session tracking!!!!

There are many ways in Java to track a session. Cookies is one of them
Let’s take a look at it below.

What is a Cookie?

A cookie is a small piece of information that is persisted between the multiple user 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.

How it works?

Once the User sends the request to the server for the first time,

1)The servlet captures the request values.

2)Creates a cookie with some values received in the request.

3)Sets that cookie in the response object and sends to User.

4)User receives that cookie in the response and caches it in the browser.

So next time when the User sends the request to the server , it also sends the cookies along with it so that the server can identify the user.

Using Cookies is the simplest way of maintaining a User state but if the cookies are disabled at the user side then it would not be possible to maintain the same.

There are 2 types of cookies in Java Servlets.

  1. Non-persistent cookie
  2. Persistent cookie

Non-persistent cookie–

It is active or you can say valid only for a single session and removed each time when user closes the browser.

Persistent cookie–

Unlike non perssitent, it is active or you can say valid for multple sessions. It is not removed when user closes the browser. It is removed only if user logs out or signs out.

Let’s look at the code implementation below.

//Creating Cookie Object
Cookie c = new Cookie("employee","James Gosling");

//Adding the Cookie object in the Response
response.addCookie(c);

//Deleting value of the cookie
Cookie c=new Cookie("employee","");
//Setting the maximum age to 0 seconds  
c.setMaxAge(0);
//Adding cookie in the Response
response.addCookie(c);

As seen above,at the server side

1)We created the cookie.

2)Added it to response object which we would be sending to user.

3)Deleted the cookie. In this we set the value of that employee as blank and set the age as 0 and added it to response. It will tell the user that the cookie is no longer be active at user side.

Let’s take a look at the servlet implementation which creates a cookie and send it to user.

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class ServletWithCookies extends HttpServlet {  
  
  public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String empName=request.getParameter("empName");  
    out.print("Hello "+empName);  
  
    Cookie c=new Cookie("employee",empName);
    response.addCookie(c);
          
    out.close();  
  
    }catch(Exception e){
      System.out.println(e.getMessage());
    }  
  }  
} 

Let’s look at UI code which sends the request to the servlet.

<form action="servlet1" method="post">  
Emp Name:<input type="text" name="empName"/><br/>  
<input type="submit" value="SEND"/>  
</form>

Below is the servlet mapping which sends the request to the correct servlet.


<web-app>  
  
<servlet>  
<servlet-name>servletcookie</servlet-name>  
<servlet-class>ServletWithCookies</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>servletcookie</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>

</web-app>