0

Handling HTTP Errors in Servlets-based application & How to avoid the IE friendly Error Page?

Posted by Guillermo GarcĂ­a on 10:56 AM in , , ,
When you develop web applications you must handle HTTP errors (like HTTP 500 Internal Server Error or the famous HTTP 404 Page Not Found)

So ... how can you handle those errors in a Servlet-based application?

The Servlet specification defined a standard method to handle HTTP Errors, in a declarative way (yeap, in the web.xml)

The "error-page" tag allows to define a handler for each HTTP error (in fact, you can also define a handler for each Exception that the servlet throws). Inside this tag you define the HTTP error that you want handle ("error-code" tag), and the handler url pattern ("location" tag).

NOTE: if you want to handle Exception instead, you must use "exception-type" instead of "error-code" tag. The exception type must be the fully qualified name of the Exception Class.

Now, the handler could be anything that can be referred by a URI (a HTML, JSP, Servlet, etc). But if you want full flexibility, you must create a Error Servlet.


A good reason (and not the only one) is this: Do you know something about the "Internet Explorer Friendly Page"? No? Well, this IE feature "prevent" ugly error pages to be displayed to the user, so, when a user gets a HTTP 404 error, in IE explorer the user will see a IE message, not your well disigned Error page, with your site template and everything. This feature is more confusing than anything, so, you must avoid it.

How can you avoid the "IE Friendly Error Page"?
Never sending an HTTP error to the client.

How can you do that if the user request an unexisting page?
Capturing the HTTP error code (with a Servlet handler), setting a new HTTP response code (like HTTP 200 OK) and showing your lovely custom error page.

How can you change/set the HTTP response code?
In the servlet, with this method (for example):
response.setStatus(HttpServletResponse.SC_OK);

0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.