Tutorial

JSP Exception Handling - JSP Error Page

Published on August 3, 2022
author

Pankaj

JSP Exception Handling - JSP Error Page

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.

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="login.jsp" method="post">
<strong>User ID</strong>:<input type="text" name="id"><br>
<strong>Password</strong>:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

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

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII" errorPage="error.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>User Home Page</title>
</head>
<body>
<%
	String user = request.getParameter("id");
	String pwd = request.getParameter("password");
	
	if(user == null || "".equals(user) || pwd == null || "".equals(pwd)){
		throw new ServletException("Mandatory Parameter missing");
	}
	
%>

<%-- do some DB processing, not doing anything for simplicity --%>
Hi <%=user %>
</body>
</html>

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.

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Error Page</title>
</head>
<body>
<% if(response.getStatus() == 500){ %>
<font color="red">Error: <%=exception.getMessage() %></font><br>

<%-- include login page --%>
<%@ include file="index.jsp"%>
<%}else {%>
Hi There, error code is <%=response.getStatus() %><br>
Please go to <a href="/index.jsp">home page</a>
<%} %>
</body>
</html>

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.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>JSPExceptionHandling</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   
   <error-page>
   <error-code>404</error-code>
   <location>/error.jsp</location>
   </error-page>
   
   <error-page>
   <exception-type>java.lang.Throwable</exception-type>
   <location>/error.jsp</location>
   </error-page>
   
</web-app>

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 29, 2018

HI Pankaj, Hope you are doing fine. !! I work on web application built on Struts 1.3 and have requirement to disable to flash player from login page. Will you be able to help? Whenever someone login to application he/she is seeing the message “Click to enable Adobe Flash player”. I just want to disable this message from login page. Can you help ?

- Milin Modi

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 5, 2014

    thank u so much sir for help :)

    - yukti singh

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 28, 2013

      Good exaplanation. Why Interrnet explorer not support for display error messages handling in jsp using iserrropage & errorpage. same app works with others browsers.

      - Siddu

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Become a contributor for community

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        DigitalOcean Documentation

        Full documentation for every DigitalOcean product.

        Resources for startups and SMBs

        The Wave has everything you need to know about building a business, from raising funding to marketing your product.

        Get our newsletter

        Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

        New accounts only. By submitting your email you agree to our Privacy Policy

        The developer cloud

        Scale up as you grow — whether you're running one virtual machine or ten thousand.

        Get started for free

        Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

        *This promotional offer applies to new accounts only.