×
DocsConsole

DocsConsole

Session Tracking With HttpSession

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

Session Tracking With HttpSession

Session will be maintained by the server to identify the current user’s state. To maintain the session, Server will generate and pass it to the client. For each request, client will append and send Session-Id to the server. So, by fetching this session id, server easily identifies that request is already associated with the session. Until and unless the client appends the session id to the request, the server will not consider the request is associated with the session.

In the current article, the example explains about the how to add the attribute in the session object. So once this added then we can use next request to identify the user to maintain the session.

Create Maven project for SessionTrackingHttpSessionApp-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, SessionTrackingURLRewritingApp-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>SessionTrackingHttpSessionApp-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SessionTrackingHttpSessionApp-Example</name>
	<description>SessionTrackingHttpSessionApp-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 create the remaining required files as given below for executing the example.

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>SessionTrackingHttpSessionApp-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>HttpSessionServlet</servlet-name>
		<servlet-class>com.docsconsole.servlet4.tutorials.HttpSessionServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>HttpSessionServlet</servlet-name>
		<url-pattern>/httpSessionServlet</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.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;

public class HomeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		try {

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

			String userName = request.getParameter("userName");
			HttpSession session = request.getSession();
			session.setAttribute("uname", userName);

			if (userName.equals("admin")) {

				out.print("<div style='padding-left: 50px; padding-top: 50px;'>");
				out.print("<span style='color: #00bcd4;'>Welcome:</span>" + userName);
				out.print("<a href='httpSessionServlet'>Visit Admin Page</a>");
				out.print("</div>");

			} else {
				request.setAttribute("message", "Sorry you are not a Admin.");
				RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
				rd.include(request, response);
			}

			out.close();

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

}
HttpSessionServlet.java
package com.docsconsole.servlet4.tutorials;

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

import java.io.*;

public class HttpSessionServlet extends HttpServlet {

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

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

			HttpSession session = request.getSession(false);
			String userName = (String) session.getAttribute("uname");

			out.print("<div style='padding-left: 50px; padding-top: 50px;'>");
			out.print("<span style='color: #00bcd4;'>Hello </span>" + userName);
			out.print("</div>");

			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>SessionTrackingHttpSessionApp-Example</h2>
		<form action="homeServlet" style="margin-bottom: 10px;">
			<span style="color: #2c2828;">Name:</span><input type="text" name="userName" /><br />
			<input type="submit" value="Send User Name" style="margin-top: 11px; background-color: #8083ef;">
		</form>
		<span style="color: red;">${requestScope.message}</span>
	</div>
</body>
</html>

The final architecture of the project application is as given below.

Session-Tracking-With-HttpSession-architecture

Please deploy and execute the application and you will get below given result page.

Session-Tracking-With-HttpSession-Result1

Please enter user name as admin otherwise you will get error message in same page.

Session-Tracking-With-HttpSession-Result
Session-Tracking-With-HttpSession-Result

Download Source Code SessionTrackingHttpSessionApp-Example.zip

Leave A Reply