1

I want to forward a request to multiple servlets in Java. Each of those servlets will perform their own operations after receiving the request.

My current code is doing this:

for(int i=0; i < numServlets; i++) {
    ServletContext servletContext = request.getServletContext();
    RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/"+ globalVars.ServletList[i]);
    requestDispatcher.forward(request, response);
}

The problem is I am getting `java.lang.IllegalStateException:

Cannot forward after response has been committed error.

Any ideas on how to make this work?

I read online that after forwaring the request I should add return statement to let the following code execute, but that did not work either.

Roman C
  • 49,761
  • 33
  • 66
  • 176
d_void
  • 123
  • 10

2 Answers2

0

If you want a request to be processed by multiple handlers, then you have a few choices:

1) Most handlers prepare or monitor data, and can be written as Filter objects, registered with the Servlet container. Only one Servlet per request is defined, which is responsible for generating the response.

2) Write one Servlet that then iterates through "handlers" and calls each of them.

3) Write multiple Servlet classes, and have all but the last forward() to the next Servlet.

I would discourage #3.

Whether #1 or #2 is better depends on what all the "servlets" are doing. E.g. it is common to write filters for:

  • Logging
  • Security (e.g. redirect to login page if not logged in)
  • Request modification (e.g. applying query parameter as request type)
  • Response processing (e.g. compression)
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Your response object is damaged. You cannot forward it unless you stop writing to the response.

Since you are forwarding it in the loop one of the servlets might commit the response before the loop ends.

One of the reason the servlet may be writing to the response or commit it in either way after response.sendRedirect() or response.sendError().

Roman C
  • 49,761
  • 33
  • 66
  • 176