Servlet Session Tracking

Session tracking is a common technique used in Web-based applications to maintain state and data of a particular user across multiple requests. Java servlets offer several ways to manage session data: HTTP cookies, URL rewriting, Hidden Form Field, and HttpSession.

Let's go through a simple example using HttpSession:

Step 1: Create a new dynamic web project

Create a new dynamic web project in your IDE.

Step 2: Create a new Servlet

Create a new servlet in your project. We'll name it "SessionServlet" for this tutorial.

Step 3: Write the Servlet code

In the created servlet, write the following code:

package com.example;

import java.io.IOException;
import java.io.PrintWriter;
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;

@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get or create the session object
        HttpSession session = request.getSession(true);

        // Get the session counter
        Integer count = (Integer) session.getAttribute("count");
        if (count == null) {
            count = 0; // start counting from 0
        }

        // Increment the counter
        count++;

        // Store the counter back into the session
        session.setAttribute("count", count);

        // Set the response content type
        response.setContentType("text/html");

        // Get the output writer
        PrintWriter out = response.getWriter();

        // Write the response content
        out.println("<html><body>");
        out.println("<h1>Session Tracking Example</h1>");
        out.println("<p>You've visited this page " + count + " time(s).</p>");
        out.println("</body></html>");
    }
}

In this servlet, we're getting the session object with request.getSession(true). The true parameter means that a new session will be created if one doesn't already exist.

We're then getting a count from the session using session.getAttribute("count"). If the count doesn't exist yet (which will be the case the first time the user visits the page), we initialize it to 0.

We increment the count, then store it back into the session with session.setAttribute("count", count).

Finally, we send a response to the user telling them how many times they've visited the page.

Step 4: Running the Servlet

Run the servlet on your server.

You should now be able to see the message from the servlet displayed in your web browser. If the server is running on your local machine, you can access your servlet at http://localhost:8080/YourProjectName/SessionServlet. Each time you refresh the page, the counter should increment.

Note: The HttpSession object is stored on the server and is associated with the user through a session ID. The session ID is usually stored in a cookie, but if the user's browser doesn't support cookies, the servlet container will use URL rewriting to append the session ID to the URL.

  1. Cookie-based session tracking in Servlets: Use cookies to associate a unique session identifier with the client.

    • Servlet automatically manages the session using the JSESSIONID cookie.
    HttpSession session = request.getSession();
    
  2. URL rewriting for session tracking in Servlet: Include the session ID in URLs for tracking.

    • Enabled by default in most Servlet containers.
    response.encodeURL("targetPage.jsp");
    
  3. Hidden form fields for session tracking in Servlets: Include the session ID as a hidden form field in HTML forms.

    • Manually add the session ID to form submissions.
    <input type="hidden" name="sessionId" value="<%= session.getId() %>">
    
  4. Session attributes in Java Servlets: Store and retrieve session attributes using the HttpSession object.

    HttpSession session = request.getSession();
    session.setAttribute("attributeName", attributeValue);
    
  5. Servlet session timeout configuration: Configure session timeout to control how long a session remains active.

    <session-config>
        <session-timeout>30</session-timeout> <!-- in minutes -->
    </session-config>
    
  6. ServletContext and ServletConfig in session tracking: Use ServletContext and ServletConfig for application-wide and servlet-specific data, respectively.

    ServletContext applicationScope = getServletContext();
    ServletConfig servletConfig = getServletConfig();
    
  7. Session fixation prevention in Servlets: Implement session fixation prevention techniques.

    • Regenerate session ID on authentication.
    HttpSession oldSession = request.getSession(false);
    request.changeSessionId();