JSP Exception Handling - JSP Error Page With Examples

Exception handling in JSP is done by JSP exception pages.

Exception Handling in JSP

Sometime back I wrote a post about Servlet Exception Handling and why do we need it. Same explanation is also applicable for JSP pages also and that’s why Java EE provides a clear approach for exception handling in JSP using JSP error pages.

To handle exceptions thrown by the JSP page, all we need is an error page and define the error page in JSP using jsp page directive.

JSP Error Page

To create a JSP error page, we need to set page directive attribute isErrorPage value to true, then we can access exception jsp implicit object in the JSP and use it to send customized error message to the client.

JSP Error Page Configuration

We need to set page directive errorPage attribute to define the JSP that will handle any exception thrown by the JSP service method. When JSP Error page is translated to servlet code, it extends org.apache.jasper.runtime.HttpJspBase in Tomcat.

Error Page Deployment Descriptor Configuration

Most of the times, we have a common error page that we want to use for all the JSPs, so rather than configuring it in all the JSPs individually, we can define error page in web.xml with error-page element. We can configure JSP error page to handle other error codes like 404 also.

Let’s see how all these fit together in a web application.

We will create a simple web application JSPExceptionHandling whose project structure will look like below image.

JSP Exception Handling, JSP error page, exception handling in jsp

The entry point of the application is index.jsp whose code is given below.

When we submit the form, request will be sent to login.jsp, code is like below.

Notice that if input parameters are null or empty, its throwing ServletException with a proper message and errorPage is defined as error.jsp whose code is like below.

Notice the isErrorPage page directive attribute value is true. When application resources throw exceptions, the error code is 500, the code is written to handle both application level exceptions and errors such as 404 – page not found.

Also notice the use of include directive to present user with login page incase of any exception.

Here is the web.xml where we are defining the error page for the application.

Now when we run above application, we get following pages as response.

Login Page
JSP exception handling example Login Page

JSP Error Page for Exception
JSP Error Page

JSP Error Page for 404 Error Code
JSP Error Code 404 Page, exception handling in JSP

Thats all for exception handling in JSP pages, its very easy to implement and we should use it to make sure we handle all the exceptions and error codes and send a useful response to client rather than container default error page.

By admin

Leave a Reply

%d bloggers like this: