×
DocsConsole

DocsConsole

Session Tracking With Cookies

By | | Updated : 2019-11-27 | Viewed : 244 times

Session Tracking With Cookies

Session Tracking Mechanisms

All the internet application will communicate with server by Https Protocol. Https protocol is stateless protocol. Means server will consider each request as new one. But it will be the problem to identify the current user. To identify the current user, requests need to be linked one to another. To make requests connect with each other, Website should maintain the user state.

The user state describes about user’s session which will be started from log in to log out. User session will be needed when a web application requires to identify current user. The managing of session is nothing Session Management which will manage about current users’ identity.

To track the session, Servlet has provided four types of approaches. We will learn here all these four types with Proc and cons;

    Types of Session Tracking Mechanisms

  • Session Tracking with Cookies

  • URL Rewriting for Session Tracking

  • Hidden fields for Session Tracking

  • HttpSession for session Tracking

Session Tracking with Cookies

Create Maven project for SessionTrackingCookiesApp-Example
Click on File tab 
--> New 
--> Click on Maven Project 
--> Please check on Create Simple Project (Skip architype selection) 
--> Click on Next --> Enter the values com.docsconsole.tutorials.servlet4 as Group Id, SessionTrackingCookiesApp-Example as Artifact Id 
--> Click on Finish
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.docsconsole.servlet4.tutorials</groupId>
	<artifactId>SessionTrackingCookiesApp-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SessionTrackingCookiesApp-Example</name>
	<description>SessionTrackingCookiesApp-Example</description>

	<properties>
		<maven.war.plugin.version>3.2.2</maven.war.plugin.version>
		<servlets.version>4.0.0</servlets.version>
		<jsp.version>2.3.1</jsp.version>
		<jstl.version>1.2.2</jstl.version>
		<tld.version>1.1.2</tld.version>
		<log4j.version>1.2.17</log4j.version>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlets.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSP Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSTL Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>${jstl.version}</version>
		</dependency>
        <!-- Taglibs -->
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${tld.version}</version>
		</dependency>
		<!-- Log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>

				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>${maven.war.plugin.version}</version>
					<configuration>
						<warSourceDirectory>src/main/webapp</warSourceDirectory>
						<warName>${project.artifactId}</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

Please crate all java, JSP and XML files with below given code. Once you override the code files we can compile and create the war for deployment.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>SessionTrackingCookiesApp-Example</display-name>

	<servlet>
		<servlet-name>HomeServlet</servlet-name>
		<servlet-class>com.docsconsole.servlet4.tutorials.HomeServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HomeServlet</servlet-name>
		<url-pattern>/homeServlet</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>CookiesServlet</servlet-name>
		<servlet-class>com.docsconsole.servlet4.tutorials.CookiesServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CookiesServlet</servlet-name>
		<url-pattern>/sendCookiesServlet</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>home.jsp</welcome-file>
	</welcome-file-list>
</web-app>
HomeServlet.java
package com.docsconsole.servlet4.tutorials;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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


public class HomeServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		
		try {

			response.setContentType("text/html");
			PrintWriter out = response.getWriter();

			String userName = request.getParameter("user");
			out.print("<span style='color: #00bcd4;'>Welcome:</span>" + userName);

			Cookie ck = new Cookie("userName", userName); // Here Cookie Object will be created
			response.addCookie(ck);// cookie will be added in the response

			// code for submit button			
			out.print("<form action='sendCookiesServlet' method='POST'>");
			out.print("<input type='submit' value='Send Cookie' style='margin-top: 10px;background: #8083ef;'>");
			out.print("</form>");

			out.close();

		} catch (Exception e) {
			System.out.println(e);
		}
		
	}
}
CookiesServlet.java
package com.docsconsole.servlet4.tutorials;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public class CookiesServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		try {

			response.setContentType("text/html");
			PrintWriter out = response.getWriter();

			Cookie cookie[] = request.getCookies();
			out.print("<span style='color: #00bcd4;'>Cookie value:</span>" + cookie[0].getValue());

			out.close();

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

}
home.jsp
<!DOCTYPE html>
<html>
<head></head>
<body>
	<div style="padding-left: 50px; padding-top: 50px;">
		<h2>Servlet Session with Coockie EXample</h2>
		<form action="homeServlet" method="post">
			<span style="color: #2c2828;">Name:</span> <input type="text" name="user" style="margin-left: 20px;"><br> <input type="submit" value="Send User Name" style="margin-top: 11px;background-color: #8083ef;">
		</form>
	</div>
</body>
</html>

Below given image will be delineated about architecture of the project.

Session-Tracking-With-Cookies-architecture

After deployment you can find below given pages result.

Session-Tracking-With-Cookies-Result1
Session-Tracking-With-Cookies-Result2
Session-Tracking-With-Cookies-Result3

Download Source Code SessionTrackingCookiesApp-Example.zip

Leave A Reply