You can catch exceptions in a JSP page like you would do in other Java classes. Simply put the code which can throw an exception/s between a try..catch block.
<%
try {
// Code which can throw can exception
} catch(Exception e) {
// Exception handler code here
}
%>
There is yet another useful way of catching exceptions in JSP pages. You can specify error page in the 'page' directive. Then if any exception is thrown, the control will be transferred to that error page where you can display a useful message to the user.
To demonstrate the run-time exception handling feature of JSP pages, we will build three pages.
* Form.html - Display a Form to the user to enter his or her age.
* FormHandler.jsp - A JSP Page which receives this value and prints it on the user screen.
* ExceptionHandler.jsp - An exception handler JSP page which is actually an error page to which control will be
passed when an exception is thrown.
Form.html page
--------------
<html>
<head>
</head>
<body>
<form action="FormHandler.jsp" method="post">
Enter your age ( in years ) :
<input type="text" name="age" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
FormHandler.jsp
---------------
<%@ page errorPage="ExceptionHandler.jsp" %>
<html>
<head>
</head>
<body>
<%-- Form Handler Code --%>
<%
int age;
age = Integer.parseInt(request.getParameter("age"));
%>
<%-- Displaying User Age --%>
<p>Your age is : <%= age %> years.</p>
<p><a href="Form.html">Back</a>.</p>
</body>
</html>
ExceptionHandler.jsp
--------------------
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
<title>Exception Occurred!</title>
</head>
<body>
<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>
</body>
</html>
Conclusion:
-----------
Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing.
No comments:
Post a Comment