
Web Pages have no memories. A user going from page to page will be treated by the website as a completely new visitor. Session cookies enable the website you are visiting to keep track of your movement from page to page so you don’t get asked for the same information you’ve already given to the site.
Cookies allow you to proceed through many pages of a site quickly and easily without having to authenticate or reprocess each new area you visit.
But sometimes in Java web applications, we should know who the client is and process the request accordingly.
For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client.
Session is a conversational state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Now let’s create Simple Dynamic Web Project in Eclipse which explains Java Servlet Session Management using Cookies.
Here are the steps:
- Create Dynamic Web Project:
CrunchifySessionManagementByCookie
crunchify-login.html
: Create welcome page of an applicationCrunchifyLoginServlet.java
– That takes care of the Login requestCrunchifyLogoutServlet.java
– That takes care of the Logout requestweb.xml
– Deployment Descriptor File (Don’t see web.xml? Follow this tutorial)CrunchifyLoginSuccessful.jsp
– Success Request is being are forwarded toLoginSuccess.jsp
, this cookie will be used there to track the session. Also notice that cookie timeout is set to 60 minutes.

Another must read:
- Spring MVC Example/Tutorial: Hello World – Spring MVC 3.2.1
- How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)
1. crunchify-login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Crunchify Login Form - Session Management by Cookies</title> <style type="text/css"> body { background-image: url('https://crunchify.com/bg.png'); } </style> </head> <body> <div align="center"> <br> <br> <form action="CrunchifyLoginServlet" method="post"> Enter Your Username: <input type="text" name="crunchifyUser"> <br> Enter Your Password: <input type="password" name="crunchifyPassword"> <br> <br> <br> <input type="submit" value="Login"> </form> </div> </body> </html>
2. CrunchifyLoginServlet.java
package com.crunchify.tutorials; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Author: Crunchify.com * */ /** * Servlet implementation class LoginServlet */ @WebServlet("/CrunchifyLoginServlet") public class CrunchifyLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final String userID = "CrunchifyUser"; private final String password = "CrunchifyPassword"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get request parameters for userID and password String crunchifyUser = request.getParameter("crunchifyUser"); String pwd = request.getParameter("crunchifyPassword"); if (userID.equals(crunchifyUser) && password.equals(pwd)) { Cookie crunchifyCookie = new Cookie("crunchifyUser", crunchifyUser); // setting cookie to expiry in 60 mins crunchifyCookie.setMaxAge(60 * 60); response.addCookie(crunchifyCookie); response.sendRedirect("CrunchifyLoginSuccess.jsp"); } else { RequestDispatcher rd = getServletContext().getRequestDispatcher("/crunchify-login.html"); PrintWriter out = response.getWriter(); out.println("<font color=red>Please make sure you enter UserID/Pass as \"CrunchifyUser : CrunchifyPassword\".</font>\n"); rd.include(request, response); } } }
3. CrunchifyLogoutServlet.java
package com.crunchify.tutorials; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Author: Crunchify.com * */ /** * Servlet implementation class LogoutServlet */ @WebServlet("/CrunchifyLogoutServlet") public class CrunchifyLogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie loginCookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("crunchifyUser")) { loginCookie = cookie; break; } } } if (loginCookie != null) { loginCookie.setMaxAge(0); response.addCookie(loginCookie); } response.sendRedirect("crunchify-login.html"); } }
4. 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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>CrunchifySessionManagementByCookie</display-name> <welcome-file-list> <welcome-file>crunchify-login.html</welcome-file> </welcome-file-list> </web-app>
5. CrunchifyLoginSuccessful.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Crunchify - Login Successful - Session management by Cookies</title> <style type="text/css"> body { background-image: url('https://crunchify.com/bg.png'); } </style> </head> <body> <div align="center"> <br> <br> <% String userName = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("crunchifyUser")) userName = cookie.getValue(); } } if (userName == null) response.sendRedirect("crunchify-login.html"); %> <h3> Hi <%=userName%>, Login successful. </h3> <br> <form action="CrunchifyLogoutServlet" method="post"> <input type="submit" value="Logout"> </form> </div> </body> </html>
Now let’s run this example:
- Deploy
CrunchifySessionManagementByCookie
Project to Tomcat and Run Tomcat.

- Point your browser URL to http://localhost:8080/CrunchifySessionManagementByCookie/crunchify-login.html

- Success Page

- Failed Login Page

Now How to Check If you Cookie is correctly set.
Try downloading any Cookie Manager Extension
and you should see Cookie
in your browser as seen below.

Let me know if you face any issue running above Servlet Cookie Management code.