How to define JSP error pages
It is a best practice to define a generic error.jsp in your web application which will display the error messages originating from various other JSP pages. Here in this JSP tutorial, you will see how to define a generic error page for two JSP pages and pass an error message to the error page. We will then print the error message on the error.jsp.
The following code shows how the first.jsp defines error JSP page:
<%@page errorPage="error.jsp" %>
<% request.setAttribute("errorMsg","First Message");%
The code for second.jsp follows:
<%@page errorPage="error.jsp" %>
<% request.setAttribute("errorMsg","Second Message");%>
The error page which is error.jsp will look like:
<%@page isErrorPage="true" %>
<%= request.getAttribute("errorMsg")%>
As one can see that in the error.jsp, we are printing the error message received from other JSP files. Also one more important point to note about error pages is that the use of isErrorPage makes available the exception implicit object to the JSP. By using the exception implicit object, we can print the stack trace as we would do in the catch handler corresponding to a try block in Java program.
In any given Java EE based web application, there shouldn't be more than 3 error JSP files depending upon the various contexts in which these error pages are required.
No comments:
Post a Comment