Introduction
The request scope makes data available to multiple pages processing the same request. But in many cases, data must be shared over multiple requests. Imagine a travel agency application. It’s important to remember the dates and destination entered to book the flight so that the customer doesn’t have to reenter the information when it’s time to make hotel and rental car reservations. This type of information, available only to requests from the same user, can be shared through the session scope. Some information is needed by multiple pages, independent of who the current user is.
JSP supports access to this type of shared information through the application scope. Information saved in the application scope by one page can later be accessed by another page, even if the two pages were requested by different users. Examples of information typically shared through the application scope are database connection pool objects, information about currently logged-in users, and cache objects that avoid unnecessary database queries for data that is the same for all users.
The figure below shows how the server provides access to the two scopes for different clients.
![Server]()
Session Tracking
Keeping track of which requests come from the same user isn’t as easy as it may look. As we know, HTTP is a stateless, request-response protocol. What this means is that the browser sends a request for a web resource; the web server processes the request and returns a response. The server then forgets this transaction ever happened. So when the same browser sends a new request, the web server has no idea that this request is related to the previous one. This is fine as long as you’re dealing with static files, but it’s a problem in an interactive web application.
There are two ways to solve this problem, and they have both been used extensively for web applications with a variety of server-side technologies. The server can either return all information related to the current user (the client state) with each response and let the browser send it back as part of the next request, or it can save the state somewhere on the server and send back only an identifier that the browser returns with the next request. The identifier is then used to locate the state information saved on the server.
In both cases, the information can be sent to the browser in one of three ways:
- As a cookie
- Embedded as hidden fields in an HTML form
- Encoded in the URLs in the response body, typically as links to other application pages (this is known as URL rewriting)
A cookie is a name/value pair that the server passes to the browser in a response header. The browser stores the cookie for the time specified by the cookie’s expiration time attribute. When the browser sends a request to a server, it checks its “cookie jar” and includes all cookies it has received from the same server (that have not yet expired)in the request headers. Cookies used for state management don’t have an expiration time and expire as soon as the user closes the browser. Using cookies is the easiest way to deal with the state issue, but some browsers don’t support cookies. In addition, a user may disable cookies in a browser that supports them because of privacy concerns. Hence, we can’t rely on cookies alone.
Sending all state information back and forth between the browser and server isn’t efficient, so most modern server-side technologies keep the information on the server and pass only an identifier between the browser and the server. This is called session tracking; all requests from a browser that contains the same identifier (session ID) belong to the same session, and the server keeps track of all information associated with the session.
JSP hides all details of cookie-based session tracking and supports the URL rewriting variety with a bit of help from the page author. In addition, the specification allows a container to use the session mechanism built into the Secure Socket Layer (SSL), the encryption technology used by HTTPS. SSL-based session tracking is currently not supported by any of the major servlet containers, but all of them support the cookie and URL rewriting techniques. No matter which mechanism is used, session data is always available to JSP pages through the session scope. Information saved in the session scope is available to all pages requested by the same browser during the lifetime of a session.
A session starts when the browser makes the first request for a JSP page in a particular application. The application can explicitly end the session (for instance, when the user logs out or completes a transaction), or the JSP container can end it after a period of user inactivity (the default value is typically 30 minutes after the last request). Note that there’s no way for the server to tell if the user closes the browser, because there’s no permanent connection between the browser and the server, and no message is sent to the server when the browser disappears. Still, closing the browser usually means losing the session ID; the cookie expires, or the encoded URLs are no longer available. So when the user opens a browser again, the server can’t associate the new request with the previous session, and therefore creates a new session. However, all session data associated with the previous session remains on the server until the session times out.
For Example. Session Tracking
<%@ page import="java.util.*" %>
<%
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = 1;
String userIDKey = "userID";
String visitCountKey = "visitCount";
String userID = "Ashish Bhatnagar";
if (session.isNew()) {
title = "Welcome to JSP";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
} else {
visitCount = (Integer) session.getAttribute(visitCountKey);
visitCount += 1;
userID = (String) session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
}
%>
<html>
<head><title>Session Tracking</title></head>
<body>
<center><h1><%= title %></h1></center>
<table border="1" align="center">
<tr bgcolor="#949494"><th>Session Info</th><th>Value</th></tr>
<tr><td>ID</td><td><%= session.getId() %></td></tr>
<tr><td>Creation Time</td><td><%= createTime %></td></tr>
<tr><td>Time of Last Access</td><td><%= lastAccessTime %></td></tr>
<tr><td>User ID</td><td><%= userID %></td></tr>
<tr><td>Number of visits</td><td><%= visitCount %></td></tr>
</table>
</body>
</html>
Code Explanation
This JSP code demonstrates the concept of session tracking by recording the number of times a user visits a web page during a session. When a user accesses the page, the server checks if the session is new. If it is, the session is initialized with default values such as a welcome message, a visit count of 1, and a user ID ("Ashish Bhatnagar"). These values are stored in session attributes.
If the session is not new, it retrieves the existing visit count and user ID from the session attributes, increments the visit count, and updates the session data. The output page then displays a dynamic welcome message along with a table showing the session ID, creation time, last access time, user ID, and the number of visits. This example illustrates how session scope in JSP allows persistent data storage for a user across multiple requests during the same session, making it useful for personalized user experiences.
Output
![Output]()
Summary
This article explains how data sharing and session tracking work in JSP (Java Server Pages) using different scopes like request, session, and application. While the request scope allows data sharing across pages during a single request, the session scope helps retain user-specific information across multiple requests, such as travel booking details. The application scope, on the other hand, stores data that is shared across all users, like database connection pools or cached objects. Since HTTP is a stateless protocol, session tracking is used to identify and manage multiple requests from the same user.
This can be achieved through cookies, hidden form fields, or URL rewriting. Among these, cookies are the most commonly used, although some users may disable them due to privacy concerns. Most modern applications prefer server-side session storage with only a session ID sent to the browser, ensuring efficient management of user states. JSP supports both cookie-based and URL-rewriting methods for session tracking. A session begins with the user's first request and ends either on logout or after a set inactivity period, usually 30 minutes. The article also includes a sample JSP program that tracks the number of visits by a user and displays session-related information such as session ID, creation time, last accessed time, user ID, and visit count using session attributes.