Session Tracking in JSP

Last updated on May 31 2022
Mohnish Patil

Table of Contents

Session Tracking in JSP

In this blog, we will discuss session tracking in JSP. HTTP is a “stateless” protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.

Maintaining Session Between Web Client and Server

Let us now discuss a few options to maintain the session between the Web Client and the Web Server −

Cookies

A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.

This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions.

Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID as follows −

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers.

This can be an effective way of keeping track of the session but clicking on a regular (<A HREF…>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.

URL Rewriting

You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session.

For example, with http://tecklearn.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client.

URL rewriting is a better way to maintain sessions and works for the browsers when they don’t support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page.

The session Object

Apart from the above-mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across.

  • a one page request or
  • visit to a website or
  • store information about that user

By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −

<%@ page session = "false" %>

The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().

Here is a summary of important methods available through the session object −

S.No. Method & Description
1 public Object getAttribute(String name)

This method returns the object bound with the specified name in this session, or null if no object is bound under the name.

2 public Enumeration getAttributeNames()

This method returns an Enumeration of String objects containing the names of all the objects bound to this session.

3 public long getCreationTime()

This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

4 public String getId()

This method returns a string containing the unique identifier assigned to this session.

5 public long getLastAccessedTime()

This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight January 1, 1970 GMT.

6 public int getMaxInactiveInterval()

This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

7 public void invalidate()

This method invalidates this session and unbinds any objects bound to it.

8 public boolean isNew()

This method returns true if the client does not yet know about the session or if the client chooses not to join the session.

9 public void removeAttribute(String name)

This method removes the object bound with the specified name from this session.

10 public void setAttribute(String name, Object value)

This method binds an object to this session, using the name specified.

11 public void setMaxInactiveInterval(int interval)

This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Session Tracking Example

This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.

<%@ page import = "java.io.*,java.util.*" %>

<%

   // Get session creation time.

   Date createTime = new Date(session.getCreationTime());

  

   // Get last access time of this Webpage.

   Date lastAccessTime = new Date(session.getLastAccessedTime());




   String title = "Welcome Back to my website";

   Integer visitCount = new Integer(0);

   String visitCountKey = new String("visitCount");

   String userIDKey = new String("userID");

   String userID = new String("ABCD");




   // Check if this is new comer on your Webpage.

   if (session.isNew() ){

      title = "Welcome to my website";

      session.setAttribute(userIDKey, userID);

      session.setAttribute(visitCountKey,  visitCount);

   }

   visitCount = (Integer)session.getAttribute(visitCountKey);

   visitCount = visitCount + 1;

   userID = (String)session.getAttribute(userIDKey);

   session.setAttribute(visitCountKey,  visitCount);

%>




<html>

   <head>

      <title>Session Tracking</title>

   </head>

  

   <body>

      <center>

         <h1>Session Tracking</h1>

      </center>

     

      <table border = "1" align = "center">

         <tr bgcolor = "#949494">

            <th>Session info</th>

            <th>Value</th>

         </tr>

         <tr>

            <td>id</td>

            <td><% out.print( session.getId()); %></td>

         </tr>

         <tr>

            <td>Creation Time</td>

            <td><% out.print(createTime); %></td>

         </tr>

         <tr>

            <td>Time of Last Access</td>

            <td><% out.print(lastAccessTime); %></td>

         </tr>

         <tr>

            <td>User ID</td>

            <td><% out.print(userID); %></td>

         </tr>

         <tr>

            <td>Number of visits</td>

            <td><% out.print(visitCount); %></td>

         </tr>

      </table>

  

   </body>

</html>

Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run the URL, you will receive the following result −

Welcome to my website

Session Information

Session info value
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 0

Now try to run the same JSP for the second time, you will receive the following result.

Welcome Back to my website

Session Information

info type value
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 1

Deleting Session Data

When you are done with a user’s session data, you have several options −

  • Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the a particular key.
  • Delete the whole session − You can call the public void invalidate() method to discard an entire session.
  • Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
  • Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
  • web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure the session time out in web.xml file as follows.
<session-config>

   <session-timeout>15</session-timeout>

</session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.

So, this brings us to the end of blog. This Tecklearn ‘Session Tracking in JSP’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn JSP and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Session Tracking in JSP"

Leave a Message

Your email address will not be published. Required fields are marked *