April 12, 2011

Exception Handling in a JSP


Write a JSP - test.jsp. Within a scriptlet in this JSP, write code that throws an Exception (for example: divide by zero Arithmetic Exception). Write another JSP - error.jsp. Display a message in this JSP that says "An unexpected error occured"
Make the error.jsp display when the client requests test.jsp

Solution


1) Create a JSP - test.jsp - in the WebContent folder with the following code that throws an ArithmeticException

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Test Page</title>
</head>
<body>

<% int i = 3/0; %>
<%-- This line will throw an ArithmeticException --%>

</body>
</html>

2) Configure exception-handling for ArithmeticException in the WebContent/WEB-INF/web.xml file

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

3) Create an error.jsp JSP in the WebContent folder with the isErrorPage attribute of the page directive set to true. This JSP has access to the exception JSP implicit object since it is now a designated error page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isErrorPage="true" %>
<html>
<head>
<title>Custom Error Page</title>
</head>
<body>

<p>This is a custom error page that displays when an ArithmeticException is thrown in any JSP</p>

<br/>
${pageContext.exception.message}

</body>
</html>

4) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/test.jsp

Note: If the EL expression ${ ... } does not print anything, set the isELIgnored attribute of the page directive to false as follows,

<%@ page ... isELIgnored="false" %>

No comments:

Post a Comment