How do I execute multiple servlets in sequence?

Use RequestDispatcher#include() on an URL matching the url-pattern of the Servlet.

public class Populate_ALL extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     response.setContentType("text/plain");
     request.getRequestDispatcher("/populateServlet1").include(request, response);
     request.getRequestDispatcher("/populateServlet2").include(request, response);
     request.getRequestDispatcher("/populateServlet3").include(request, response);
     //...
  }
}

Note: if those servlets cannot be used independently, then this is the wrong approach and you should be using standalone Java classes for this which does not extend HttpServlet. In your specific case, I think the Builder Pattern may be of interest.

The RequestDispatcher#forward() is not suitable here since it throws IllegalStateException when the response headers are already committed. This will be undoubtely the case when you pass the request/response through multiple servlets which each writes to the response.

The HttpServletResponse#sendRedirect() is absolutely not suitable here since it implicitly creates a brand new request and response, hereby trashing the original ones.

See also:

Leave a Comment