How do I share data between servlets using ServletContext?

In Java Servlets, you can share data between servlets using the ServletContext object. The ServletContext is an application-wide object that all servlets in a web application can access. It allows servlets to share information. Here’s how you can use it:


Steps to Share Data Using ServletContext:

  1. Set Attribute in ServletContext:
    • A servlet can store an object in the ServletContext as an attribute using the setAttribute method.
    ServletContext context = getServletContext();
    context.setAttribute("sharedData", "This is shared data");
    
  2. Retrieve the Attribute in Another Servlet:
    • Another servlet can retrieve the shared data using the getAttribute method.
    ServletContext context = getServletContext();
    String sharedData = (String) context.getAttribute("sharedData");
    
  3. (Optional) Remove the Attribute:
    • If needed, you can remove the attribute using the removeAttribute method.
    context.removeAttribute("sharedData");
    

Example Use Case:

Create two servlets: one for setting the data and one for retrieving it.

SetDataServlet.java

package org.kodejava.servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/setData")
public class SetDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set shared data in ServletContext
        ServletContext context = getServletContext();
        context.setAttribute("sharedData", "Hello from SetDataServlet!");

        response.getWriter().println("Data set successfully.");
    }
}

GetDataServlet.java

package org.kodejava.servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/getData")
public class GetDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve shared data from ServletContext
        ServletContext context = getServletContext();
        String sharedData = (String) context.getAttribute("sharedData");

        response.getWriter().println("Shared Data: " + sharedData);
    }
}

Key Points:

  1. Application Scope:
    • Attributes in the ServletContext are available globally across the web application. They can be accessed by all servlets and JSPs.
  2. Thread-Safety:
    • Be cautious about thread safety because servlets handle multiple requests concurrently. If multiple threads modify the shared data simultaneously, data consistency issues may occur.
    • You may need to synchronize access to the shared object.
  3. Lifecycle:
    • Attributes in the ServletContext remain in memory until they are explicitly removed using removeAttribute, or the application is redeployed/stopped.

Advanced Sharing via ServletContextListener:

If you need to initialize or clean up shared data when the application starts or stops, you can use a ServletContextListener.

package org.kodejava.servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.setAttribute("sharedData", "Initial shared data");
        System.out.println("Application started. Shared data set.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Application stopped. Cleaning up...");
    }
}

This ensures shared data is set and removed in a centralized manner.


This approach to sharing data is straightforward and works seamlessly for many use cases in a web application.

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.