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" %>
Qui开发者_运维问答te 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?
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.
精彩评论