Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 290
Maro Avatar asked May 24 '11 22:05

Maro


People also ask

What is the status code in HTTP?

An HTTP status code is a server response to a browser's request. When you visit a website, your browser sends a request to the site's server, and the server then responds to the browser's request with a three-digit code: the HTTP status code.

Which is the correct options about the status of the HTTP response?

Answer is "A status of 400 to 499 indicates an error in the server"

What is an HTTP status code and what are the most common ones?

Status Code 404 – The most common status code the average user will see. A status code 404 occurs when the request is valid, but the resource cannot be found on the server. Even though these are grouped in the Client Errors “bucket,” they are often due to improper URL redirection.


1 Answers

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.

like image 171
Asaf Avatar answered Oct 02 '22 00:10

Asaf