Introduction to Session Management using Cookies

Cookies are text files stored on the client computer and they are kept for various information tracking purpose.

There are three steps involved in identifying returning users:

  1. Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  2. Browser stores this information on local machine for future use.
  3. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.


Advantage of Cookies

  • Simplest way to maintain conversation state of the client(browser).
  • Cookies are maintained at client side.

Cookies are text files stored on the client computer and they are kept for various information tracking purpose.

There are three steps involved in identifying returning users:

  1. Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  2. Browser stores this information on local machine for future use.
  3. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.


Advantage of Cookies

  • Simplest way to maintain conversation state of the client(browser).
  • Cookies are maintained at client side.


Disadvantage of Cookies

  • It will not work if user disabled cookies from the browser.
  • Only textual information can be set in Cookie object.

Cookies API:

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.


Constructor of Cookie class

  Cookie() :-It will constructs a cookie.

  Cookie(String name, String value):-It will constructs a cookie with a specified name and value.

Before moving forward to the Servlet Session Management API, I would like to show how can we keep track of session with cookies through a small web application.

Step 1 : Create Dynamic Web Project

Open Eclipse IDE and create a dynamic web project. Provide the name of the project as CookiesExample.

We will create a dynamic web application CookiesExample with project structure like below image.

session management cookies example

Step 2 : Create welcome page of an application

login.html is welcome page of our application where we will get authentication details from user.

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>Login Form - Session Management by Cookies</title>

</head>

<body>

	<div align="center">
		<br> <br>
		<form action="loginServlet" method="post">
			Enter Your Username: <input type="text" name="userName"> <br>
			Enter Your Password: <input type="password" name="password">
			<br> <br> <br> <input type="submit" value="Login">
		</form>
	</div>
</body>
</html>

Step 3 : Create Servlet(Controller) Class

Create a java class LoginServlet that takes care of the login request.

LoginServlet.java
package com.jwt.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * Author: Mukesh
 * 
 */

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String userID = "mukesh";
	private final String pwd = "kumar";

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// get request parameters for userID and password
		String user = request.getParameter("userName");
		String password = request.getParameter("password");

		if (userID.equals(user) && pwd.equals(password)) {
			Cookie loginCookie = new Cookie("user", user);
			// setting cookie to expiry in 30 mins
			loginCookie.setMaxAge(30 * 60);
			response.addCookie(loginCookie);
			response.sendRedirect("loginSuccess.jsp");
		} else {
			RequestDispatcher requestDispatcher = getServletContext()
					.getRequestDispatcher("/login.html");
			PrintWriter out = response.getWriter();
			out.println("Either user name or password is wrong.");
			requestDispatcher.include(request, response);
		}

	}

}
LogoutServlet.java
package com.jwt.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * Author: Mukesh
 * 
 */

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String userID = "mukesh";
	private final String pwd = "kumar";

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// get request parameters for userID and password
		String user = request.getParameter("userName");
		String password = request.getParameter("password");

		if (userID.equals(user) && pwd.equals(password)) {
			Cookie loginCookie = new Cookie("user", user);
			// setting cookie to expiry in 30 mins
			loginCookie.setMaxAge(30 * 60);
			response.addCookie(loginCookie);
			response.sendRedirect("loginSuccess.jsp");
		} else {
			RequestDispatcher requestDispatcher = getServletContext()
					.getRequestDispatcher("/login.html");
			PrintWriter out = response.getWriter();
			out.println("Either user name or password is wrong.");
			requestDispatcher.include(request, response);
		}

	}

}

Above class is controller class for logout request. There is no method to remove the cookie but we can set the maximum age to 0 so that it will be deleted from client browser immediately.

Step 4 : Create LoginSuccess.jsp file

loginSuccess.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>Login Success Page</title>
</head>
<body>
<%
String userName = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
    if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
if(userName == null) response.sendRedirect("login.html");
%>
<h3>Hi <%=userName %>, Login successful.</h3>
<br>
<form action="logoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>

Now let’s run this example:

Deploy CookiesExample Project to Tomcat and Run Tomcat.

Point your browser URL to http://localhost:8080/CookiesExample/ session management in java


Success Page

session management in java

Failed Login Page

session management in java

You can download the source code of the example by clicking on the Download link below.

Source : Download
Source + Lib : Download




comments powered by Disqus