I’m trying to include a jsp page from a servlet:
RequestDispatcher rd = ctx.getRequestDispatcher( jspPage );
rd.include( req, wrapper );
But I’m getting the following exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
The problem is with a JSP page that specifies its own default error page through the JSP error tag. The JSP error page can also throw an exception which will trickle up to the application level error page specified in web.xml. So when the jsp page that I am trying to include throws an exception, and the error page throws an exception as well, the include fails.
I have to handle this case gracefully because I am including user-written modules on a page and an erroneous module should display the exception to the user rather than bomb with the IllegalStateException. Any ideas?
As already hinted in a comment in your previous question, it’s simply too late to change the response. After a X amount of bytes in the response, the response headers will be committed to the client and this is a point of no return. You need to rewrite your JSP’s. They should contain only markup and presentation logic and not any business logic which can throw exceptions.
If you really can’t refactor the erroneous business code in your JSP’s into fullworthy servlet/business classes, there where they belongs, then your best bet is to increase the HTTP response buffer size in the server config and pray that nowhere a
flush()is been invoked before the exception occurs in the JSP and you don’t getOutOfMemoryErrorfailures when it gets busy on your webapp.Related questions: