Hello ranchers,
I am confused about what is allowed after calling the forward()-method:
RequestDispatcher rd =
request.getRequestDispatcher("/ServletB");
rd.forward(request, response);
// What is allowed here?
David Bridgewater writes:
"What you can't do in ServletA - after the forward call - is anything that might attemt to affect the response. Well, you can do it - and the lines of code will execute harmlessly, having no effect."
That means, I can write into the response (this would not lead to an
IllegalStateException), but I cannot flush the response (this would lead to an IllegalStateException).
Charles Lyons writes:
if (condition) {
rd.forward(request, response);
return;
}
response.setHeader("myheader", "myvalue");
"If we'd omitted the explicit return statement from above, the subsequent header modification would be executed and an IllegalStateException would be thrown since the response is committed."
A few pages later Charles Lyons writes:
"When forward() is invoked, it clears the current buffer. (...) When this method returns, the response should be considered committed, we shouldn't ideally write any more content to the response stream, but it isn't illegal to do so."
What is definitely allowed within the forwarding
Servlet after returning from the forward()-method and without throwing a RuntimeException:
- Writes into the response without flushing.
- Sets a response-header.
- Both of them.
- Nothing of them.
Regards
Oliver