English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Session Tracking

HTTP is a "stateless" protocol, which means that each time the client retrieves a web page, the client opens a separate connection to the Web server, and the server automatically does not retain any records of the previous client requests.

However, there are still three ways to maintain the session between the Web client and the Web server:

Cookies

A web server can assign a unique session session ID as a cookie for each web client, and the received cookie can be used to identify the client for subsequent requests.

This may not be a valid method because many browsers do not support cookies, so we recommend not using this method to maintain session.

Hidden form field

A web server can send a hidden HTML form field and a unique session 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 keep track of different web browsers.

This may be an effective way to maintain session tracking, but clicking on regular hyperlinks (e.g., <A HREF...>) does not cause form submission, so hidden form fields do not support regular session tracking.

URL rewriting

You can append some additional data at the end of each URL to identify the session, and the server will associate the session identifier with the stored session data.

For example, http://oldtoolbag.com/file.htm;sessionid=12345, the session session identifier is appended as sessionid=12345, the identifier can be accessed by the web server to identify the client.

URL rewriting is a better way to maintain session, which works well when the browser does not support cookies, but its disadvantage is that it dynamically generates each URL to assign a session session ID, even for very simple static HTML pages.

HttpSession object

In addition to the three methods mentioned above, Servlet also provides the HttpSession interface, which provides a way to identify users across multiple page requests or visits to the website and store relevant user information.

The Servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session lasts for a specified period of time, across multiple connections or page requests.

You will pass through calling the public method of HttpServletRequest getSession() to obtain the HttpSession object, as shown below:

HttpSession session = request.getSession();

You need to call this before sending any document content to the client request.getSession().The following summarizes several important methods available in the HttpSession object:

Serial NumberMethod & Description
1public Object getAttribute(String name)
This method returns the object with the specified name in the session; if no object with the specified name is present, it returns null.
2public Enumeration getAttributeNames()
This method returns an enumeration of String objects that contain the names of all objects bound to the session.
3public long getCreationTime()
This method returns the time, in Greenwich Mean Time, when the session was created. 1970 Years 1 Month 1 Starting from midnight of the day, in milliseconds.
4public String getId()
This method returns a string containing the unique identifier assigned to the session.
5public long getLastAccessedTime()
This method returns the time, in Greenwich Mean Time, when the client last sent a request related to the session. 1970 Years 1 Month 1 Starting from midnight of the day, in milliseconds.
6public int getMaxInactiveInterval()
This method returns the maximum time interval, in seconds, that the Servlet container keeps the session open when the client accesses it.
7public void invalidate()
This method invalidates the session and unbinds any objects bound to it.
8public boolean isNew()
This method returns true if the client does not know about the session or if the client chooses not to participate in the session.
9public void removeAttribute(String name)
This method removes the object with the specified name from the session.
10public void setAttribute(String name, Object value)
This method binds an object to the session using the specified name.
11public void setMaxInactiveInterval(int interval)
This method specifies the time interval between client requests, in seconds, before the Servlet container indicates that the session is invalid.

Session tracking example

This example demonstrates how to use the HttpSession object to obtain the session creation time and the last access time. If the session session does not exist, we will create a new session session through the request.

package com.w3codebox.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
    {
        // If the session session does not exist, create a session object
        HttpSession session = request.getSession(true);
        // Obtain the session creation time
        Date createTime = new Date(session.getCreationTime());
        // Get the last access time of this webpage
        Date lastAccessTime = new Date(session.getLastAccessedTime());
         
        //Set the date output format  
        SimpleDateFormat df=new SimpleDateFormat("yyyy--dd HH:mm:ss  
    
        String title = "Servlet Session Example - Basics Tutorial Website";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        3codebox
        if(session.getAttribute(visitCountKey) == null) {
            session.setAttribute(visitCountKey, new Integer(0));
        }
    
        // Check if there is a new visitor on the webpage
        if (session.isNew()){
            title = "Servlet Session Example - Basics Tutorial Website";
             session.setAttribute(userIDKey, userID);
        } else {
             visitCount = (Integer)session.getAttribute(visitCountKey);
             visitCount = visitCount + 1;
             userID = (String)session.getAttribute(userIDKey);
        }
        session.setAttribute(visitCountKey, visitCount);
    
        // Set the 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>Access Statistics:</td>\n" +
                "  <td>" + visitCount + "</td></tr>\n" +
                "</table>\n" +
                "</body></html>"); 
    }
}

Compile the above Servlet SessionTrack, and create the appropriate entry in the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet> 
    <!-- class name -->  
    <servlet-name>SessionTrack</servlet-name>
    <!-- the package where it is located -->
    <servlet-class>com.w3codebox.test.SessionTrack</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SessionTrack</servlet-name>
    <!-- The visited URL -->
    <url-pattern>/TomcatTest/SessionTrack</url-pattern>
  </servlet-mapping>
</web-app>

Enter the URL in the browser address bar http://localhost:8080/TomcatTest/SessionTrack, when you run it for the first time, it will display the following result:

Try running the same Servlet again, it will display the following result:

Delete Session session data

When you have completed a user's session session data, you have the following options:

  • Remove a specific attribute:You can call public void removeAttribute(String name) method to delete the value associated with a specific key.

  • Delete the entire session:You can call public void invalidate() method to discard the entire session.

  • to set the session timeout.You can call public void setMaxInactiveInterval(int interval) method to set the session timeout individually.

  • Log out user:If you are using a servlet-supported 2.4 server, you can call logout to log out the client of the Web server and invalidate all sessions belonging to all users.

  • web.xml Configuration:If you are using Tomcat, in addition to the above method, you can configure session timeout in the web.xml file as follows:

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

The timeout time in the above example is in minutes and will override the default 30 minutes timeout.

The getMaxInactiveInterval() method in a Servlet returns the session timeout time in seconds. Therefore, if the session timeout time is configured as 15 minutes, then getMaxInactiveInterval() will return 900.