Friday, April 29, 2011

Chapter 49: Web Application Exceptions

Your Web application will have errors, all software products do. No one can claim that they have developed a bug-free code. Well, if they do, they need to be frozen and displayed in the museum of extinct species. Jokes apart, any systems strength depends on how gracefully it can handle exceptions.

In this chapter, we are going to see how the deployment descriptor can be used to handle exceptions.

So, lets get started!!!

Web Application Exceptions

The servlet specification addresses the need to handle errors. The following snippet shows you how to use the error-page element, which defines which resource the container should use for a given exception.
< web-app >
< error-page >
< error-code > 404 < / error-code >
< location > /404.html < / location >
< / error-page >
< / web-app >

With this definition, the client will get the 404.html page if it requests a page that the container cannot find.

You can accomplish the same thing a little more dynamically with the RequestDispatcher. You can forward a request to an error page easily like so:

ServletContext context = getServletContext();
dispatcher = context.getRequestDispatcher("/errors/error.jsp");

Although this is more dynamic, it ignores all kinds of rules for good practice. It would be better to use the error-page element most of the time but forward to an error page with the RequestDispatcher on occasion.

You can also specify the exception handling declaratively in the deployment descriptor. You do this with the error-page element and the exception-type subelement like so:

< web-app >
< error-page >
< exception-type > javax.servlet.ServletException < / exception-type >
< location > /servlet/ErrorDisplay < / location >
< / error-page >
< / web-app >

This is a good practice as it makes the intention explicit for your Web application as opposed to relying on defaults.

Previous Chapter: Chapter 48 - Elements of the Deployment Descriptor

Next Chapter: Chapter 50 - Web Application Security

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.