How can I share a variable or object between two or more Servlets?

I think what you’re looking for here is request, session or application data.

In a servlet you can add an object as an attribute to the request object, session object or servlet context object:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String shared = "shared";
    request.setAttribute("sharedId", shared); // add to request
    request.getSession().setAttribute("sharedId", shared); // add to session
    this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context
    request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);

If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:


If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user:


Until the session expires based on inactivity from the user.

Is reset by you:


Or one servlet removes it from scope:


If you put it in the servlet context it will be available while the application is running:


Until you remove it:


Leave a Comment