Thursday, February 13, 2014

JSP Exception Handling

JSP Exception Handling:

Exception Handling is a process of handling exceptional condition that might occur in your application. Exception Handling in JSP is much easier than Java Technology exception handling. Although JSP Technology also uses the same exception class object.

It is quite obvious that you dont want to show error stack trace to the guy surfing your website. You can't prevent all errors in your application but you can atleast give an user friendlier error response page.

Ways to perform exception handling in JSP:

JSP provide two different way to perform exception handling.

    Using isErrorPage and errorPage attribute of page directive.
    Using <error-page> tag in Deployment Descriptor.

Example of isErrorPage and errorPage attribute

isErrorPage attribute in page directive officially appoint a JSP page as an error page.

error.jsp:

<%@ page isErrorPage = "true" %>
<html>
     <body>
    //Error message
     </body>
</html>

Exception handling in Jsp:

errorPage attribute in page directive tells the Web Container that if an exception occur in this page, forward the request to an error page.

sum.jsp:

<%@ page errorPage = "error.jsp" %>
<html>
     <body>
    <% int x =20/0; %>
    the Sum is <%= x %>
     </body>
</html>

Exception handling in Jsp:

Declaring error page in Deployment Descriptor

You can also declare error pages in the DD for the entire Web Apllication.Using <error-page> tag in Deployment Descriptor you can even configure different error pages for different exception types, or HTTP error code type(400,500 etc.).

Declaring an error page for all type of exception

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>

Declaring an error page for more detailed exception

<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error.jsp</location>
</error-page>

Declaring an error page based on HTTP Status code

<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

 

No comments:

Post a Comment