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 errors 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.
We have define 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 comes up and show the exception messages.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="/errorPage.jsp" %>
<title>My Sample Page</title>
<h1>This page throws an error:</h1>
int number = Integer.parseInt("Hello, World!");
In this example we are going to learn how to use <jsp:include> action. This action can be use to include resource dynamically to our JSP pages. For example the resource can be another JSP page, a servlet or event a static html pages. But to make it enable to be processed as a JSP page, such as accepting parameters, we must use the .jsp as the file extension. If we use other extension such as .jspf, it will processed as a static page.
The other things to note is that using the <jsp:include> action will process the page inclusion at the request time. This is why we can pass parameters to the included page using the <jsp:param>. The value can be read by obtaining the parameter from the request object or using expression language variable param.
But if we use the <%@ include %> directive the inclusion of the page happen when it translated into a Servlet. See the following example about the <%@ include %> directive: How do I include a page fragment into JSP?