I have a JSP page (in Tomcat) which uses JSP Tags to retrieve some data. But these JSP Tags can throw exceptions (For example when parameter values are invalid). Now I want to implement a nicer error handling for these situation. I failed to find a way to GLOBALLY specify an exception handler (error-page definitions in web.xml don't work for exceptions thrown in a JSP). The only way I found so far is specifiying an errorPage attribute in the page header of ALL JSP-files.
<% page errorPage="/WEB-INF/jsp/errors/500.jsp" %>
Quite annoying to do this for ALL JSPs, but acceptable. But not acceptable is the fact that the error page is always delivered with a HTTP status code of 200. I want a 500 instead. I tried using a servlet as errorPage instead of a JSP and tried to set response.setStatus(500) and also response.sendError(500) but both calls seems to be ignored. So this code prints "200" two times and I have no idea why:
System.out.println(response.getStatus());
response.setStatus(500);
System.out.println(response.getStatus());
So the question is: How can I set the HTTP status code in JSP error handlers?
There are two ways of handling exceptions in JSP. They are: By errorPage and isErrorPage attributes of page directive. By <error-page> element in web.
To create a JSP error page, we need to set page directive attribute isErrorPage value to true, then we can access exception jsp implicit object in the JSP and use it to send customized error message to the client.
A JSP page can specify its own default error JSP page from an exception that is occurring within it, through the JSP error tag. This enables a JSP page to specify its own handling of an error.
The first type of JSP error occurs when a JavaServer Page is first requested and goes through the initial translation from a JSP source file into a corresponding servlet class file. These errors are usually the result of compilation failures and are known as translation time errors.
You can configure your error pages in web.xml
.
<error-page>
<error-code>
500
</error-code>
<location>
/500.jsp
</location>
</error-page>
in your 500.jsp
, set the directive as <%@ page isErrorPage="true" %>
Instead of setStatus(500)
, you'd better use sendError(500)
- there are some differences.
The config in web.xml
works fine with sendError
, however, if you don't want the config in web.xml
, error-page
from page directive worked just for exceptions for me, not for HTTP error codes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With