Error Pages in JSP 2.0

We can configure error pages in jsp and servlets to direct the control to a custom error page, showing a friendly error message to the user when an exception is thrown in the page. But tracking or logging the exception information is not very easy in JSP 1.2.

also read:

JSP 2.0 fixes this problem by switching to the servlet specification: javax.servlet.error.exception. In addition, a new property of the implicit EL pageContext variable, named errorData, exposes other information about the problem. The errorData property is an instance of the javax.servlet.jsp.ErrorData class that can be used as a bean with the following properties:

<table border="1" width="55%" style="background-color:#EFEFEF">
	<tr align="center">
		<td width="10%"><b>Property</b></td>
		<td width="12%"><b>Java Type</b></td>
	<tr align="left">
		<td>The URI for the request that failed.</td>
		<td>The name of the servlet or JSP page that failed.</td>
		<td>The failure status code. </td>
		<td>The exception that caused the error page to be invoked.</td>

1) File Name : firstPage.jsp

<%@page errorPage="/jsp/errorpage.jsp" contentType="text/html" %>
	<title>Error Pages in JSP 2.0</title>
		String s = null;

2) File Name : errorpage.jsp

<%@page isErrorPage="true" contentType="text/html" %>
		Request that failed: ${pageContext.errorData.requestURI}
		Status code: ${pageContext.errorData.statusCode}
		Exception: ${pageContext.errorData.throwable}

3) Output

Request that failed: /TestWebApp/jsp/firstPage.jsp
Status code: 500
Exception: java.lang.NullPointerException


In the first page I declare a null string and I call a function on it. The JSP engine will encounter faulty code and will throw a NullPointerException. As I have configured an error page in the page directive the control is taken to the errorpage.jsp.

In the error page I use properties of errorData to display useful information about the exception. This information is useful for the developer to track down the problem quickly and efficiently as he will know exactly which page threw the exception and what was the type of exception.



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind