Session Tracking in JSP

Session Tracking in JSP with Examples

In this article, I am going to discuss Session Tracking in JSP with Examples. Please read our previous article where we discussed Filters in JSP with Examples. At the end of this article, you will understand the following pointers with examples that are related to JSP Session Tracking.

  1. Overview of JSP Session tracking
  2. What is a Session?
  3. Session Management in Java
  4. What is Session Tracking in JSP?
  5. The need for Session Tracking
  6. Session Tracking Techniques
  7. Cookies
  8. Hidden Form Fields
  9. URL Rewriting
  10. The Session Object
  11. How to get a Session object
  12. Methods of the session object
  13. JSP Session Tracking Examples
  14. JSP session invalidate
  15. Browser Session vs. Server Session
  16. Store Attributes in Session object wisely
Overview of Session Tracking

As part of the web application development, it is essential to manage the client’s previous request data at the time of processing later request. To achieve the above requirement if we use a request object then the container will create a request object when it receives a request from the client and the container will destroy the request object when it dispatches the response to the client. Due to this reason request object is not sufficient to manage the client’s previous request data at the time of processing later request. To achieve the above requirement, we able to use the ServletContext object, but the ServletContext object will share its data to all the components which are used in the present applications and to all the users of the present web application. Due to this reason, the ServletContext object is unable to provide a clear-cut separation between multiple users. In web applications, to manage the client’s previous request data at the time of processing later request and to provide separation between multiple users we need to set mechanisms explicitly at the server-side called Session Tracking Mechanisms.

What is a Session?

A session is a time duration; it will start from the starting point of the client conversation with the server and will terminate at the ending point of the client’s conversation with the server. The data which we transferred from client to server through multiple numbers of requests during a particular session then that data is called State of the Session.

In general, in web applications, a container will prepare a request object similarly to represent a particular user we have to prepare a separate session. In this context, to keep track of all the session objects at the server machine we need to set explicit mechanisms called Session Tracking Mechanisms.

Session Management in Java

Session Management is used to recognize the particular user. It is a way to maintain the state (data) of the user about a series of requests from the same user (that is, requests originating from the same browser) across the same period of time. Each time the user requests to the server, the server always treats the request as the new request.

What is Session Tracking?

In our applications sometimes we need to carry or transfer the data between multiple forms. But in form-based applications, we are using HTTP protocol which is a stateless protocol which means it remembers only the current conversation. For example, if we leave the first form and enter it into the second form, we will forget about the previous form data. But if we want to overcome this limitation and carry the data between multiple forms, we can use any one of the following methodologies:

  1. Hidden variables
  2. Cookies
  3. Sessions
  4. A session with URL re-writing or encoding URL
Need for Session Tracking in JSP

Whenever a client makes a request, then for each request a new connection is established to the webserver because HTTP is a stateless protocol. It is very difficult for servers to identify that the requests are coming from the same user or not because every time a new connection is established. In this case, the server does not keep track of the information of the previous request if every time a new request is made.

To overcome this problem, for every request a unique id should be possessed which helps to maintain a complete conversation between the client and server.

Session Tracking Techniques

Hidden Variables

If we want to use variables, we have to use hidden fields given by HTML. Hidden fields must be specified as a part of <form> and we must specify name and value attributes. Hidden fields not displayed to the client.

Syntax: <input type=”hidden” name=”xxx” value=”yyy”/>

Advantages:
  1. Hidden variables consume less memory.
  2. Once we close the browser the data of hidden variables will be cleared automatically.
Disadvantages:
  1. If we want to carry a huge amount of data then it will be complicated using hidden variables.
  2. Hidden variables are not recommended to carry any sensitive data.
Cookies

Cookies are also used to transfer the data between multiple form-based applications. Simply a cookie is a small piece of information sent by the server to any client. Every cookie will store the data in the form of key-value pair. The server will add the cookie to the response header by using the Set-Cookie header and send it to the client. Cookies will be stored in the browser by using the domain name of the website. The browser can contain cookies from multiple domains. The client needs to use HeaderCookie to get all the cookies available in the browser.

Syntax: Cookie myCookie = new Cookie(“SessionID”, “SessionValue”)

Advantage:
  1. Compared to hidden variables cookies are better to transfer the data because once we store the cookie, we can get the data on any page of the website directly.
Disadvantage:
  1. If the client disables the cookies in the browser we can work with cookies.
  2. For security reasons, it is not recommended to use cookies.
  3. If we want to a huge amount of data between server and client it will be complicated.
URL Rewriting

By appending the sessionId at the end of the link we can rewrite the URL as follows:

http://localhost:8080/jsp/home.jsp?sessionid=”ABC”

By using this unique identifier, the server can easily identify the user which is also known as handling the browsers. When the user clicks on the rewritten link, the servlet gets and recognizes the SessionID by which the HTTP session will get the Session ID.

Advantage:
  1. We don’t need to pass hidden values here.
  2. This method is useful even if the user has disabled cookies.
  3. URL Rewriting technique is independent of the browser.
Disadvantage:
  1. The client needs to append the sessionID and regenerate the URL with each request.
  2. Also, the client needs to keeps track of the unique ID until the conversation ends between the client and the server.
Session Object in JSP

Creating a session object means creating an object for a class that is implementing javax.servlet.HttpSession interface. The session object is also used to transfer the data between multiple form-based applications. In the case of servlets, we have to write the code for creating the session object. But in JSP by default session object is enabled whenever the client sends the request to the server internally. So, we can write the JSP program directly to get Session information. In the JSP session is an implicit object. But if we want to handle session object in JSP explicitly then we have to write the following page re-directive in the JSP program:

<%@ page session=”false|true”%>

Advantage: This technique is more reliable as each user has its own unique sessionID which is helpful to access the session data stored at the server-side.

How to get Session Object?

When the client sends the request to the server for the first time then the server creates a session object and now the server creates a unique ID that is associated with this session object. Then the server will create a cookie with the name JSESSIONID which holds the session object as a value and send it to the client. If we want to request the server to create a session object, we have to use the following methods of request object:

HttpSession getSession(true)
HttpSession getSession(false)

Session objects are used to store the data. The session can support to stores of any kind of data. To work with the session object and to store the data or to get the data we have to use some set of methods.

Methods of Session Object
  1. getAttribute(String name): It gives the object bound with the specified name in this session.
  2. getAttributeNames(): It gives an Enumeration of String objects containing the names of all the objects bound to this session.
  3. getCreationTime(): It returns the time when this session was created.
  4. getId(): It returns a string containing the unique identifier assigned to this session.
  5. getLastAccessedTime(): It returns the last time the client sent a request associated with this session.
  6. getMaxInactiveInterval(): It returns the maximum time interval that the servlet container will keep this session open between client accesses.
  7. invalidate(): It invalidates the session and unbinds any objects bound to it.
  8. isNew(): It returns true if the client does not yet know about the session or if the client chooses not to join the session.
  9. removeAttribute(String name): It removes the object bound with the specified name from this session.
  10. setAttribute(String name, Object value): It binds an object to this session using the specified name.
  11. setMaxInactiveInterval(int interval): It specifies the time between client requests before the servlet container will invalidate this session.
When session object is deleted?
  1. When we close the server.
  2. When we call session.invalidate() in our program generally session.invalidate() is called as a part of logout pages.
  3. When we call session.setMaxInactiveInterval(int) in our program.
  4. By changing the session timeout in web.xml of the server.
Session Tracking Examples in JSP: Printing Session Info

In this example, we will see how to use the HttpSession object to find out the creation time and the last accessed time for a session. A new session has associated with the request if one does not already exist.

SessionObject.jsp
<%@ 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>

 <h1>Session Tracking</h1>


 <table border="1">
  <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>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <display-name>SessionTracking</display-name>
 <welcome-file-list>
  <welcome-file>SessionObject.jsp</welcome-file>
 </welcome-file-list>
</web-app>
Output

Run your code to get the following output:

Session Tracking in JSP with Examples

If you will load the page again, the number of visits will increase accordingly.

Session Tracking in JSP

Example: Session Invalidate

For invalidating the session in the above code, we need to append the following code <%session.invalidate();%>. Here the current session gets invalidated and the number of visits sets to 1. Even on reloading the page, the value is not increasing as the session has been invalidated and objects are free. The complete code is as follows:

SessionObject.jsp
<%@ 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>
 <h1>Session Tracking</h1>

 <table border="1">
  <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>
 <%
  session.invalidate();
 %>
</body>
</html>
Output

Run your code to get the following output:

JSP Session Tracking

Browser Session vs. Server Session
Browser Session
  1. It stores all the user data stored in cookies.
  2. In a browser session, it is not required to replicate the nodes and validate the session.
  3. Here, session validation is faster and super scalable.
  4. We need to encrypt and signing the cookie using a server key for security measures.
  5. Cookies can be dropped from the browser as sessions cannot be revoked immediately.
Server Session
  1. It is commonly used because its cookie size is small.
  2. It allows for replicating session data across all web servers.
  3. If the server faces any problem and needs to be shut down, users will encounter issues accessing data.
  4. Here the user details are more secure.
  5. Because of its efficient access, the users will always reach out to the same web server.
Store Attributes in Session object wisely
  1. It is very convenient to store attributes in session.
  2. One needs to very careful while storing attributes in session as they can be modified by another JSP.
  3. Suppose we are using two JSP pages in our application where one JSP page calls some data and pulls it put and stores it in a session for later use. But we have another JSP page that updates the values in the database of the session variable. Also, there is another developer who is working on your web application and he/she doesn’t know that you have already created a session variable and he/she also thought of creating the same and stores some value in it. Now if JSP written by the second developer gets executed before the first, then it will change the session variable and will update the data in the database accordingly. So, it is recommended to use session variables wisely.

In the next article, I am going to discuss JSP Cookies Handling with Examples. Here, in this article, I try to explain JSP Session Tracking with Examples. I hope you enjoy this Session Tracking in JSP with Examples article.

Leave a Reply

Your email address will not be published.