Search code examples
jsphttp-redirectcustom-error-pages

Can't Redirect From JSP Error Page Or Flush Browser Buffer


I’m trying to improve the error handling of a Java / JSP web app and ran into a problem using JSP’s error page. If an exception is not handled during the processing of a page, the JSP error page is redirected to.

I noticed that when the error page is processed the output stream from before the error occurred has been committed to the browser and consequently the browser ends up with partial output from before the error occurred and whatever the error page is supposed to display, which isn’t what I want to display or correct from a HTML perspective.

I’ve investigated and found that there doesn’t appear to be away to force a flush of the browser’s buffer and replace it with just the error page output once the output stream has been committed. I looked at flushing the output stream and using JavaScript to force the page to clear:

<script>
window.stop();
document.body.innerHTML = "";
</script>

I also tried to redirect to a completely different URL using JSP’s response.sendRedirect(url) but it doesn’t redirect or flush the page. Why doesn’t this work?

So, in the end I used plain old HTML to redirect after error page processing and that works as intended. My error page is Error.jsp:

<%@ page isErrorPage="true" %>

<%
    String url = "ErrorDisplay?msg=" + URLEncoder.encode( exception.toString(), "UTF-8");
%>

<!-- This redirects -->
<meta http-equiv="Refresh" content="0; url=<%= url %>">

ErrorDisplay.jsp:

<h1>An error has occurred: <%= request.getParameter("msg") %></h1>

Update 5/19/19 -- So the redirect fix doesn't always work. I still have portions of the error causing page's output stuck in the browser and that causes the redirect HTML to not be recognized as redirect HTML but as just text output. Any ideas how to make a JSP error page work when the error comes after there has been partial output to the browser?


Solution

  • I found a solution. Adding these lines to the above Error.jsp file forces the browser (at least FireFox) to flush its current page on the redirect to ErrorDisplay.jsp.

    <meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="expires" content="0" />