Force a response to be commited in a servlet

790 Views Asked by At

a code is better than an explanation :

in my servlet :

...
this.getServletContext
   .getRequestDispatcher("..../foo.jsp")
        .forward(request, response); // (1)

// (2)

this.getServletContext
   .getRequestDispatcher("..../bar.jsp")
        .forward(request, response); // (3)
...

if i call the url related to this servlet, I get the following error :

"Cannot forward after response has been committed"

because (1) set the jsp to use, (3) try to set another jsp. (notice : I know it is bad example but this is to provide a minimal code).

What I want is to "stop" the servlet to process any further instructions after (1) :

  • (1) is set
  • (2) writing something to say I want (1) to be used
  • (3) not to be read

How can I do that ?

2

There are 2 best solutions below

0
On

A simple solution would be to have something like this:

this.getServletContext.getRequestDispatcher("..../foo.jsp")
    .forward(request, response);

if(!response.isCommitted()) {
    this.getServletContext.getRequestDispatcher("..../bar.jsp")
        .forward(request, response);
}

From the Java docs:

boolean isCommited():

Returns a boolean indicating if the response has been committed. A committed response has already had its status code and headers written.


Or, if as you say above, the first block of code is dependent on the user having limited permissions:

if (isUserRestricted()) {
    this.getServletContext.getRequestDispatcher("..../foo.jsp")
        .forward(request, response);
} else {
    this.getServletContext.getRequestDispatcher("..../bar.jsp")
        .forward(request, response);
}
0
On

Ok, first The exception is caused when you forward the request when the response was flused or closed, for example when close the PrintWriter or flush the ServletOutputStream and after that you forward. You could use include instead of forward in the Request Dispatcher that method call the resource but returns to the caller. So I suggest you to have an if conditional to check if you want to forward the request, or flush the response.