Servlet Session Tracking
HTTP is a "stateless" protocol, which means that each time a client retrieves a webpage, the client opens a separate connection to the web server, and the server automatically does not retain any records of previous client requests.
However, there are still three ways to maintain a session between the web client and the web server:
Cookies
A web server can assign a unique session ID as a cookie for each web client, and subsequent requests from the client can use the received cookie to identify the client.
This may not be an effective method because many browsers do not support cookies, so we recommend not using this method to maintain sessions.
Hidden Form Fields
A web server can send a hidden HTML form field along with a unique session ID, as shown below:
<input type="hidden" name="sessionid" value="12345">
This entry means that when the form is submitted, the specified name and value will be automatically included in the GET or POST data. Each time the web browser sends back a request, the session_id value can be used to track different web browsers.
This may be an effective way to maintain session tracking, but clicking on regular hypertext links (e.g., <A HREF...>
) does not result in form submission, so hidden form fields do not support regular session tracking.
URL Rewriting
You can append some additional data to the end of each URL to identify the session. The server will associate this session identifier with the stored session data.
For example, http://w3cschool.cc/file.htm;sessionid=12345
, the session identifier is appended as sessionid=12345
, and the identifier can be accessed by the web server to identify the client.
URL rewriting is a better way to maintain sessions, as it works well when the browser does not support cookies. However, its drawback is that it dynamically generates each URL to assign a session ID to the page, even in simple static HTML pages.
HttpSession Object
In addition to the above three methods, Servlet provides the HttpSession interface, which offers a way to identify a user across multiple page requests or visits to a website and to store information about that user.
The Servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified period of time, across multiple connections or page requests.
You will obtain the HttpSession object by calling the public method getSession() of HttpServletRequest, as shown below:
HttpSession session = request.getSession();
You need to call request.getSession() before sending any document content to the client. The following summarizes several important methods available in the HttpSession object:
No. | Method & Description |
---|---|
1 | public Object getAttribute(String name) <br> This method returns the object in the session with the specified name, or null if no object with that name exists. |
2 | public Enumeration getAttributeNames() <br> This method returns an enumeration of String objects containing the names of all objects bound to the session. |
3 | public long getCreationTime() <br> This method returns the time when the session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
4 | public String getId() <br> This method returns a string containing the unique identifier assigned to the session. |
5 | public long getLastAccessedTime() <br> This method returns the time when the client last sent a request associated with the session, measured in milliseconds since midnight January 1, 1970 GMT. |
6 | public int getMaxInactiveInterval() <br> This method returns the maximum time interval, in seconds, that the servlet container will keep the session open between client accesses. |
7 | public void invalidate() <br> This method invalidates the session and unbinds any objects bound to it. |
8 | public boolean isNew() <br>This method returns true if the client does not yet know about the session or if the client chooses not to participate in the session. |
9 | public void removeAttribute(String name) <br>This method will remove the object with the specified name from the session. |
10 | public void setAttribute(String name, Object value) <br>This method binds an object to the session with the specified name. |
11 | public void setMaxInactiveInterval(int interval) <br>This method specifies the time, in seconds, between client requests before the Servlet container will invalidate the session. |
Session Tracking Example
This example demonstrates how to use the HttpSession object to get the session creation time and the last access time. If no session exists, we will create a new session through the request.
package com.tutorialpro.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class SessionTrack
*/
@WebServlet("/SessionTrack")
public class SessionTrack extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Create a session object if it does not exist
HttpSession session = request.getSession(true);
// Get session creation time
Date createTime = new Date(session.getCreationTime());
// Get the last access time of this web page
Date lastAccessTime = new Date(session.getLastAccessedTime());
// Set date output format
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String title = "Servlet Session Example - tutorialpro.org";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("tutorialpro");
if(session.getAttribute(visitCountKey) == null) {
session.setAttribute(visitCountKey, new Integer(0));
}
// Check if there is a new visitor
if (session.isNew()) {
title = "Servlet Session Example - tutorialpro.org";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer) session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String) session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE html>\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Information</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session Information</th><th>Value</th></tr>\n" +
"<tr>\n" +
" <td>ID</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + df.format(createTime) +
" </td></tr>\n" +
"<tr>\n" +
" <td>Last Access Time</td>\n" +
" <td>" + df.format(lastAccessTime) +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Visit Count:</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
Compile the SessionTrack Servlet and create the appropriate entries in the web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<!-- Class Name -->
<servlet-name>SessionTrack</servlet-name>
<!-- Package Location -->
<servlet-class>com.tutorialpro.test.SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<!-- URL to access -->
<url-pattern>/TomcatTest/SessionTrack</url-pattern>
</servlet-mapping>
</web-app>
Enter http://localhost:8080/TomcatTest/SessionTrack in the browser address bar. When you run it for the first time, the following result will be displayed: