Home > Articles

  • Print
  • + Share This

Handling Exceptional Conditions

Had the user entered an invalid year, a sight equivalent to the "blue screen of death" would flash before the user's eyes. Figure 3.5 displays the output in the browser had the user entered "aaaa" for the year:

Figure 3.5 shows an exception that occurred in the JSP indicating that the parseInt method couldn't parse the data. The exception is propagated to the user in case there are no error-handling routines. Such sights could rattle visitors to your site or users of your application, so much so that that they might never visit it again.

Figure 3.5 A Runtime Exception propagated to the browser

There are different ways to prevent and handle such exceptional conditions. You might want to use some or all of the following mechanisms:

  • Using error pages

  • Performing client-side validations using a scripting language

  • Performing server-side validations in the JSP

Using Error Pages

In the event of an exception occurring on the server side, you might want to gracefully exit by specifying error pages for your JSPs. When exceptions occur within the JSP, the JSP container will automatically redirect to the error page. Error pages will trap arbitrary runtime exceptions and are good indications of bugs in the program.

You need to create an error page, error.jsp, that displays a generic error as shown in Listing 3.7.

Listing 3.7 error.jsp: Displaying a Generic Error Message

<%@ page isErrorPage="true" %>
<html>
<head>
 <title>Oops!</title>
</head>
<body>
<h1>We are sorry</h1>
The page you have just reached has some errors.
Our technical staff has been informed of the error and will fix it 
as soon as possible.
<p>
Error: <%= exception.getMessage() %>
<p>
Thank you for your patience
</body>
</html>

To specify error.jsp as the error page for JSPs, modify page directives to include the errorPage parameter:

<%@ page import="java.util.*, java.text.DateFormat" errorPage="error.jsp" %>

Figure 3.6 shows the error page as displayed in a browser when the user inputs an invalid year.

Figure 3.6 The Error Page displayed on an error

You can enhance the error JSP to send an email informing the support staff about the error as shown in the next chapter. In this way they can take corrective action to fix the bug.

Performing Client-Side Validations Using JavaScript

The second approach to preventing such an erroneous situation from occurring is to nip it at its bud. You can embed validation routines in your input page defined using a client-side scripting language. This way the user's data can be checked before being sent to the server, and also reduce network traffic by preventing roundtrips from the server.

Most browsers today support at least one client-side scripting language, with JavaScript being the most popular among them all. You can create routines using these scripting languages to check whether the data supplied by the user is valid, and alert the user of the mistake right away, without having to send the request with the incorrect data to the server.

JavaScript enables you to access different elements of your document using the Document Object Model and also provides some methods to operate on basic data types.

The Document Object Model provides a programmatic access to the document. Each element of the document is a part of the hierarchy with the window containing the document as the root. In JavaScript such elements are known as Navigator Objects.

You can access and update each Navigator Object in the document with JavaScript by using its location within the hierarchy. For example, to retrieve the title of the document being displayed in the window, you can use document.title. To access the value of the month input field within the form named monthform you can use document.monthform.month.value in your JavaScript routine.

In Listing 3.8, the Submit button has been replaced with a JavaScript enhanced button. It defines a handler for the onClick method passing the form in which the event occurred as a parameter. The validation method extracts the value of the year field, parses it, and checks if the number obtained from that operation is a valid one. If it is not valid, determined from the return value of the isNan() operation, it opens an alert window displaying the error message as shown in Figure 3.7. If it is valid, it submits the form to the server. No checks need to be done for the month field because the input is constrained to the values displayed in the drop-down list.

Figure 3.7 Alert displayed using JavaScript on an invalid input

Listing 3.8 input.jsp: Validation Routine Written in JavaScript

<html>
<head>
 <title>Calendar Input Page</title>
<script language="JavaScript">

<!-- Hide script from old browsers
function validate(f) {
 intValue = parseInt(f.year.value);
 if (isNaN(intValue)) {
 alert("Please enter a valid year");
 return false;
 }
 else {
 f.submit();
 }
}
// End hiding -->

</script>
</head>
<body>
 <center><h1>Calendar Viewer</h1></center>
 <table border=0 WIDTH="500" >
 <tr>
  <td></td>
  <td width="80%"><font size=+2>Overview</font> <br>Provide the Month
  and Year andclick on the Submit button to view the Calendar for 
  the Month. <p><br>
  <form method="get" action="month.jsp" name="monthform"
   onSubmit="validate(this)">
  <table border="0" >
  <tr>
   <td width="40%"><b>Month:</b></td>
   <td><select name="month">
    <option value="0">January</option>
    <option value="1">February</option>
    <option value="2">March</option>
    <option value="3">April</option>
    <option value="4">May</option>
    <option value="5">June</option>
    <option value="6">July</option>
    <option value="7">August</option>
    <option value="8">September</option>
    <option value="9">October</option>
    <option value="10">November</option>
    <option value="11" selected="true">December</option>
   </select></td>
  </tr>
  <tr>
   <td><b>Year:</b></td>
   <td><input type="text" name="year" size="20" maxlength="4">
   </td>
  </tr>
  </table>
  <br><p>
  <input TYPE="button" NAME="Submit" VALUE="Submit"
   onClick="validate(this.form)">
  <input TYPE="reset" NAME="Reset" VALUE="Reset">
  </form></td>
 </tr>
</table>
</body>
</html>

NOTE

You should provide the onSubmit handler in the form tag as well. This allows the browser to validate the form data when the user submits the form by hitting the Enter button.

Performing Server-Side Validations

Client-side validations aren't always the recommended error-handling mechanism because of the following reasons:

  • The browser might not support JavaScript. Older browsers might not support any scripting languages.

  • The user might have disabled the feature.

  • If the GET request method is being used, the user can set the value of the parameters by altering the URL, thus bypassing the validation routines as shown in Figure 3.8.

Figure 3.8 Manually specifying the parameters by altering the URL in the browser

You should validate the user values within the JSP and should process the values only if they have passed the validation. In the monthly calendar JSP, you should check whether the month and year provided by the user are valid integral values. You should also provide the user with feedback about the data and the mistakes in them that they provided.

Let's alter the scriptlet that reads the request parameters and initializes the java.util.Calendar instance. First, you need to create a declaration for a string representing the message you want to send across to the user when an invalid year is specified. Now enclose the potentially troublesome code within a try-catch block. In this case it's when you parse the year string to its integral equivalent.

If the operation results in an exceptional condition, forward the request to the input JSP, passing the error message as a parameter, so that the user can retry sending the information. In the JSP forward tag you need to specify the name of the JSP to which the request needs to be redirected, input.jsp in this case. You can also specify additional parameters, such as the error message for the year field, yearMsg, and the error message for the month field, monthMsg.

The JSP forward tag can not be included within the scriptlet, hence the scriptlet needs to be divided into two parts, as shown in Listing 3.9:

  • For parsing the request parameters and catching the exceptions.

  • For closing the if block in the previous scriptlet and for setting the values in the calendar instance.

Listing 3.9 input.jsp: Validation Routine in the JSP

<%! public final static String INVALID_YEAR = "Please enter a valid year," +
  " without any spaces, alphabets and special characters";
 public final static String INVALID_MONTH = "Please enter a valid month"; %>
<%
 int month = -1;
 int year = -1;
 String monthError = "";
 String yearError = "";
 try { month = Integer.parseInt(request.getParameter("month"));
 } catch Exception exc) {
  monthError = INVALID_MONTH;
 }

 // Validate the year
 try {
  year = Integer.parseInt(request.getParameter("year"));
 } catch (Exception exc) {
  yearError = INVALID_YEAR;
 }

 if (!(monthError.length() == 0 && yearError.length() == 0)) {
%>

 <jsp:forward page="input.jsp">
 <jsp:param name="yearMsg" value="<%= yearError%>"/>
 <jsp:param name="monthMsg" value="<%= monthError%>"/>
 </jsp:forward>

<% }
 cal.set(year, month, 1);
%>

You also need to alter input.jsp to allow the error message to be displayed. Input.jsp will be used for accepting the first time input as well as for the retries.

The error message that was passed as a parameter in the forward tag can be obtained just like any other request parameter from the 'request' implicit object by specifying the parameter name.

A good place to display the error message in a Web document is next to the source itself. Displaying the error message in a different color allows the user to notice the message. You can add the error message for the year next to the year label and display it with a red color to highlight the problem as shown in Listing 3.10.

Listing 3.10 input.jsp: Validation Routine in the JSP

<tr>
 <td><b>Year:</b><br>
 <font color="red" size="-2">
 <% 
  String yearMsg = request.getParameter("yearMsg");
  out.println(((yearMsg == null) ? "": yearMsg));
 %>
 </font>
 </td>
 <td valign="top">
 <input type="text" name="year" size="20" maxlength="4">
 </td>
</tr>

You might also want to set the valid values within the input.jsp so the user doesn't have to enter it again. Earlier, you saw how the options for the menu could be generated dynamically by using a scriptlet. You need to enhance the scriptlet to allow the option representing the valid month to be selected in the drop-down list as shown in Listing 3.11.

Listing 3.11 input.jsp Enhancing the Generate Month Options Scriptlet to Display Existing Selections

<%! String[ ] monthNames = (new DateFormatSymbols()).getMonths(); %>
<% 
 int month = 11;
 try {
 month = Integer.parseInt(request.getParameter("month"));
 } catch (Exception exc) {
 }

 // Print all the options
 for (int i = 0; i < 12 ; i++) {
 out.print("<option value=\""+ i + "\"");
 if (i == month) {
  out.print(" selected=\"true\"");
 }
 out.println(">" + monthNames[i] + "</option>");
 } // end for-loop
%>

Figure 3.9 shows the error message displayed in the input page when an incorrect year is specified.

Figure 3.9 The Revamped Input Page displaying error information

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.