A generic mechanism to deal with HTTP status codes
I know you can specify error pages in web.xml as below
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
I find it a bit tedious to list a page for each and every error code. I was wondering what would be the best common practice in this situation! Is there a better way to generate these pages automatically such as using a JSP 开发者_运维知识库or servlet or via Spring or Stripes?
If you're talking about the generation of the page itself, you can map an error code to a jsp page, e.g.
<error-page>
<error-code>404</error-code>
<location>/errors.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/errors.jsp</location>
</error-page>
if you're talking about the mapping itself, a possible solution (though I'd advise you to use the standard web.xml mapping) to avoid mapping of all error codes is to use a servlet filter which filters all resources, delegates access to the FilterChain and checks the response code set if it is not 200 (or any other predefined acceptable responses such as 401) and than redirects to the errors.jsp page.
In order to capture the response code you'll to wrap the HttpServletResponse with a HttpServletResponseWrapper implementation that saves the response code set.
Stripes provides a few extensible yet simple ways to handle exceptions. There is a good writeup on the stripes website and a few pages in the Stripes book about it.
You'll essentially either implement the ExceptionHandler interface, extend from DefaultExceptionHandler (what we've typically done), or there is DelegatingExceptionHandler for more advanced situations.
精彩评论