YouTip LogoYouTip

Servlet Session Tracking

Servlet Session Tracking

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 a web client and a web server:

Cookies

A web server can assign a unique session ID to each web client as a cookie. The client can use the received cookie for subsequent requests to identify itself.

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 keep track of different web browsers.

This may be an effective way to maintain session tracking, but clicking a regular hyperlink (<A HREF...>) does not cause a form submission, so hidden form fields also 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 that session identifier with the stored session data.

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

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

HttpSession Object

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

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 across multiple connections or page requests.

You 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 some important methods available in the HttpSession object:

NumberMethod & Description
1 public Object getAttribute(String name)
This method returns the object bound to this session with the specified name, 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 this session, as measured in 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 indicates that this session is invalid 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 illustrates how to use the HttpSession object to get the session creation time and last access time. If a session does not exist, we will create a new one by request.

package com.tutorial.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 does not exist, create a new session object
        HttpSession session = request.getSession(true);
        // Get 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-MM-dd HH:mm:ss");  
     
        String title = "Servlet Session Example - Tutorial";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        String userID = new String("Tutorial");
        if(session.getAttribute(visitCountKey) == null) {
            session.setAttribute(visitCountKey, new Integer(0));
        }

     
        // Check if the webpage has a new visitor
        if (session.isNew()){
            title = "Servlet Session Example - Tutorial";
            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>Visit Count:</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>
    <!-- Package -->
    <servlet-class>com.tutorial.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:

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

Deleting Session Data

When you are done with a user's session data, you have several options:

  • Remove a specific attribute: You can call the public void removeAttribute(String name) method to delete the value associated with a specific key.
  • Delete the entire session: You can call the public void invalidate() method to discard the entire session.
  • Set session timeout: You can call the public void setMaxInactiveInterval(int interval) method to set the session timeout individually.
  • Log out the user: If you are using a server that supports Servlet 2.4, you can call logout to log out the client from the web server and invalidate all sessions belonging to all users.
  • web.xml configuration: If you are using Tomcat, in addition to the above methods, you can also configure the session timeout in the web.xml file, as shown below:
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

The timeout in the above example is in minutes and will override the default 30-minute timeout in Tomcat.

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

Servlet Cookie Handling

Servlet Database Access

← Servlet Database AccessServlet Cookies Handling β†’