The JSP Files (part 7): Bugs, Beans And Banks - You Throw(), I'll Catch
(Page 5 of 7 )
It's also possible to use the Java "throw" construct to artificially induce an exception in your JSP script. This comes in handy, for example, when validating form field data - if the values entered are not in the expected format, you can throw an exception (with an informative error message) and re-direct the user to an error page.
Here's an example of how this can be used. This is a simple form which asks you to enter a number
<html>
<head>
<basefont face="Arial">
</head>
<body>
<form action="number.jsp">
Enter a number between 1 and 3 <input type=text name=number size=1>
</form>
</body>
</html>
and this is the server-side JSP script which checks it
for errors, and throws an exception if certain conditions are not met.
<html>
<head>
<basefont face="Arial">
</head>
<body>
<%@ page errorPage="error.jsp" %>
<%
String temp = request.getParameter("number");
int number = Integer.parseInt(temp);
if (number != 2)
{
throw new Exception ("How dumb can you get?!") ;
}
else
{
out.println("Hmmm...maybe you're not as dumb as you look!");
}
%>
</body>
</html>
Next up, a brief look at JavaBeans and how they integrate
with the JSP environment.
Next: Bean Bag >>
More Java Articles
More By Vikram Vaswani and Harish Kamath, (c) Melonfire