Signup/Sign In

Using Cookies for Session Management in Servlet

Cookies are small pieces of information that are sent in response from the web server to the client. Cookies are the simplest technique used for storing client state.

Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.

Using Cookies for storing client state has one shortcoming though, if the client has turned of COokie saving settings in his browser then, client state can never be saved because the browser will not allow the application to store cookies.


Servlet: Cookies API

Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to response object.

session management using cookie


Example demonstrating usage of Cookies

cookies example

Below mentioned files are required for the example:


index.html

<form method="post" action="validate">
    Name:<input type="text" name="user" /><br/>
    Password:<input type="text" name="pass" ><br/>
    <input type="submit" value="submit">
</form>

web.xml

<web-app...>
    
    <servlet>
        <servlet-name>validate</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>validate</servlet-name>
        <url-pattern>/validate</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
</web-app>

MyServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        if(pass.equals("1234"))
        {
            Cookie ck = new Cookie("username", name);
            response.addCookie(ck);
            response.sendRedirect("First");
        }
    }
}

First.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cks = request.getCookies();
        out.println("Welcome "+ cks[0].getValue());
    }
}

Types of Cookies


There are two types of cookies. They are as following:

  • Session
  • Persistent

1) Session cookies:

The session cookies do not have any expiration time. It is present in the browser memory. When the web browser is closed then the cookies are destroyed automatically.

2) Persistent Cookies:

The Persistent cookies have an expiration time. It is stored in the hard drive of the user and it is destroyed based on the expiry time.


How cookies works?

When a user Start a web and request information from the website. The website server replies and it sends a cookie. This cookie is put on the hard drive. Next time when you return to the same website your computer will send the cookies back. Now the website server identifies the data and sale your information to other sellers.


demo5.html


    
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="abc" method="post">
Enter User name: <input type="text" name="val1"><br>
Enter Password: <input type="text" name="val2"><br>
<input type="submit" value="go">
</form>
</body>
</html>
    

cookie1.html


    
package com.app.studytonight;

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class cookie1 extends HttpServlet {  
  
  public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
    String n=request.getParameter("val1");  
    out.print("Welcome "+n);  
    Cookie ck=new Cookie("uname",n);  
    response.addCookie(ck); 
    out.print("<form action='pqr' method='post'>");  
    out.print("<input type='submit' value='go'>");  
    out.print("</form>");  
    out.close();  
        }
    catch(Exception e)
    {
        System.out.println(e);
    }  
  }  
}  
    

cookie2.html


    
package com.app.studytonight;
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class cookie2 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);
    }  
    }  
} 
    

web.xml


    
<servlet>  
<servlet-name>s1</servlet-name>  
<servlet-class>com.app.studytonight.cookie1</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>s1</servlet-name>  
<url-pattern>/abc</url-pattern>  
</servlet-mapping>  
  
<servlet>  
<servlet-name>s2</servlet-name>  
<servlet-class>com.app.studytonight.cookie1</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>s2</servlet-name>  
<url-pattern>/pqr</url-pattern>  
</servlet-mapping>  
  </web-app> 
    

cookies-example-output