In this example you will learn how to handle exceptions in JSP page. JSP have a build-in mechanism for error handling which is a special page that can be used to handle every error in the web application. To define a page as an error page we use the page
directive and enable the isErrorPage
attribute by setting the value to true
.
Here is an example of a JSP error page:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Error Page</title>
</head>
<body>
<h1>An error has occurred.</h1>
<div style="color: #F00;">
Error message: <%= exception.toString() %>
</div>
</body>
</html>
We have defined the error page. The next steps is how to tell other JSP pages to use the error page to handle errors when uncaught exception occurred. To do this we again use the page
directive. Set the errorPage
attribute of this directive to point to the error page. For instance in the example below we set it to errorPage.jsp
.
If we try to access the errorTest.jsp
as shown in the snippet below. It will throw an exception because we try to convert an invalid string into a number. Because we are not handling the error in the page the error page will come up and show the exception messages.
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page errorPage="/errorPage.jsp" %>
<html lang="en">
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>This page throws an error:</h1>
<%
int number = Integer.parseInt("Hello, World!");
%>
</body>
</html>