There are two ways to define Error page in Java web application written using Servlet and JSP. First way is page wise error page which is defined on each jsp page and if there is any unhanded exception thrown from that page, corresponding error page will be displayed. Second approach is an application wide general or default error page which is shown if any Exception is thrown from any Servlet or JSP and there is no page specific error page defined.
In this java tutorial we will see both approach to declare error page in JSP and when should we use page specific error page and when should we choose generate default application wide error page in Java web application. This is in continuation of my earlier post on Servlet and JSP like top 10 Servlet interview questions and top 10 JSP interview questions.
Page Specific Error page in JSP
Every JSP page has an attribute called "errorpage" on page directive, by using this attribute you can define an error page for any particular JSP. After that if any unhandled Exception thrown from that JSP , this error page will be invoked. In order to make any JSP page as an error page you need to use "isErrorPage" attribute of page directive and mark it true. For example in below JSP pages error.jsp is an error page which can be used to display custom error messages if any unhandled exception is thrown from login.jsp (because it is defined as errorpage for login.jsp)
<%@ page isErrorPage="true"%>
<%@ page errorPage="error.jsp"%>
This is preferred way of showing error messages in Java web application if you have custom error messages based on JSP and it also supersede any application wide error page defined in web.xml.
Error page in Java Web Application JSP Servlet
Application wide Error page in Java web application
There is another way to define error pages in java web application written using servlet and JSP. This is called application wide error page or default/general error page because its applicable to whole web application instead of any particular servlet or JSP. Its recommended practice for every Java web application to have a default error page in addtion of page specific error pages. This error page is defined in web.xml by using tag <error-page>. <error-page> allows you to define custom error message based upon HTTP error code or any Java Exception. you can define a default error message for all exception by specifying <exception-type> as java.lang.Throwable and it would be applicable to all exception thrown form any Servlet or JSP from web application. here is an example of declaring default error page in Java web application based on HTTP Error code and Java Exception type.
That's all on how to define custom error page in Java application both page specific and an application wide default error page.Important point to note is that page specific error pages takes precedence over application wide default error page defined in web.xml.