Web Application Context and Data Sharing

The application context provides a scope for sharing data across all requests and sessions within a web application. Data stored in this context remains available throughout the application's lifecycle, from startup to shutdown.

The application context is created when the web application starts and is destroyed when the application shuts down. It allows data to be accessed from any part of the application at any time during its execution.

To store data in the application context:

package com.example.web;

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

@WebServlet("/store-data")
public class DataContextWriter extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        ServletContext context = request.getServletContext();
        
        List<String> items = new ArrayList<>(Arrays.asList("item1", "item2", "item3"));
        context.setAttribute("sharedList", items);
        context.setAttribute("userRole", "administrator");
        context.setAttribute("userName", "JohnDoe");
    }
}

To retrieve data from the application context:

package com.example.web;

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

@WebServlet("/retrieve-data")
public class DataContextReader extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        ServletContext context = getServletContext();
        
        List<String> sharedItems = (List<String>) context.getAttribute("sharedList");
        System.out.println(sharedItems);
        System.out.println(context.getAttribute("userRole"));
        System.out.println(context.getAttribute("userName"));
    }
}

Tags: servlet application-context web-development data-sharing Java-EE

Posted on Tue, 06 Oct 2026 16:41:58 +0000 by delphi123