Enable jsp page with redirect errors from servlet

I am trying to include a jsp page from a servlet:

RequestDispatcher rd = ctx.getRequestDispatcher( jspPage ); rd.include( req, wrapper ); 

But I get the following exception:

 java.lang.IllegalStateException: Cannot forward after response has been committed 

The problem is with the JSP page, which points to its own default error page through the JSP error tag. The JSP error page may also throw an exception that leaks to the application-level error page specified in web.xml. Therefore, when the jsp page that I am trying to include throws an exception and the error page also throws an exception, the inclusion fails.

I need to handle this case gracefully, because I turn on user-written modules on the page, and the wrong module should display an exception for the user, and not bomb using IllegalStateException. Any ideas?

+4
source share
2 answers

As the comment in the previous question already hinted at, it is just too late to change the answer. After X number of bytes in the response, the response headers will be sent to the client, and this is the point of no return. You need to rewrite your JSPs. They should contain only markup and presentation logic, and not any business logic that can throw exceptions.

If you really cannot reorganize the erroneous business code in your JSP into full-fledged servlet / business classes, where they exist, it is best to increase the size of the HTTP response buffer in the server configuration and pray that flush() n’t anywhere thrown before the exception occurs in the JSP, and you don't get an OutOfMemoryError error when it is busy on your web server.

Related questions:

0
source

Can you try redirecting the user's browser to the error page? You may need to save any error information that you want to display to the user in the session, so the error page may display it.

The only problem is that the redirect message may fail because the content has already been delivered from the faulty “page”. Not sure if this is very bulletproof :)

Perhaps increasing the size of the buffer may make it work across multiple pages.

0
source

Source: https://habr.com/ru/post/1334589/


All Articles