Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Managing Data Within the HttpSession Scope

Tech 2

Scope Validity

Data stored in the HttpSession object remains accessible throughout the duration of a user's interaction with the web application. It persists across multiple request-response cycles within a single browser sesssion.

Lifecycle Events

  • Initialization: The container creates a session object when a request is made and the session does not already exist.
  • Active Usage: The session remains valid while the user interacts with the application. The server maintains this state across different pages or resources.
  • Termination: The session ends when the browser closes (losing the session ID cookie), the server invalidates it manually, or the session times out due to inactivity.

Implementation Examples

Storing Attributes

The following servlet demonstrates initializing a session and populating it with various attributes, including a collection of values.

package com.example.webapp;

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;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebServlet("/saveData.action")
public class SessionWriter extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve or create the current session context
        HttpSession userSession = request.getSession();

        // Prepare a list of items
        List<String> items = Arrays.asList("Alpha", "Beta", "Gamma");
        userSession.setAttribute("itemCollection", items);

        // Store simple string attributes
        userSession.setAttribute("userRole", "Administrator");
        userSession.setAttribute("status", "Active");
        userSession.setAttribute("username", "JohnDoe");

        // Forward the request to the reader servlet
        response.sendRedirect("loadData.action");
    }
}

Retrieving Attributes

This servlet reads the data previously stored in the session and outputs it to the console.

package com.example.webapp;

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

@WebServlet("/loadData.action")
public class SessionReader extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession userSession = request.getSession();

        // Optional: Remove a specific attribute from the session
        // userSession.removeAttribute("status");

        // Extract attributes from the session scope
        List<String> retrievedItems = (List<String>) userSession.getAttribute("itemCollection");
        String role = (String) userSession.getAttribute("userRole");
        String user = (String) userSession.getAttribute("username");

        // Log the session data
        System.out.println("Retrieved List: " + retrievedItems);
        System.out.println("User Role: " + role);
        System.out.println("Username: " + user);

        // Extract parameters specifically from the current HTTP request (not session)
        System.out.println("Query Param 'id': " + request.getParameter("id"));
        System.out.println("Query Param 'type': " + request.getParameter("type"));
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.