Input Validation and html:errors


Input Validation and <html:errors>

This section provides information on the following tag:

  • <html:errors> ” Output error text to the user

If you point your browser to the URL

 http://myAppServer/StrutsTaglibs/html.jsp 

you'll bring up the main page that links to all the sample code for the Struts tag chapters. This section uses <html:errors> Sample Code page at /StrutsTaglibs/HtmlErrors.do .

This page is shown in two different stages. The first stage, shown in Figure 12.6, shows the page as it appears when no validation errors have occurred.

Figure 12.6. The <html:errors> Sample Code page with no errors shown at /StrutsTaglibs/HtmlErrors.do .

graphics/12fig06.gif

Figure 12.7 displays the same file with errors showing. Simply checking the check box element and submitting the form generates these errors. Two types of errors are shown: a global error that's shown at the form level, and a field-level error shown for just the check box element itself.

Figure 12.7. The <html:errors> Sample Code page with global and field-level errors shown at /StrutsTaglibs/HtmlErrors.do .

graphics/12fig07.gif

Listing 12.8 is the JSP file that creates this page.

Listing 12.8 JSP File Demonstrating Use of the <html:errors> Tag for Both Global and Form-Level Errors ( HtmlErrors.jsp )
 <%@ page language="java" %> <%@ page import="org.apache.struts.action.*" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html:html> <head> <title>&lt;html:errors&gt; sample code</title> </head> <body bgcolor="white"> <h1>&lt;html:errors&gt; sample code</h1> <b>1. &lt;html:errors property="org.apache.struts.action.GLOBAL_ERROR"/&gt;</b> <br>This will display page-level errors, if any, right here:<p> <html:errors property="org.apache.struts.action.GLOBAL_ERROR"/> <hr> <b>2. &lt;html:errors bundle="ch12.HtmlErrors" /&gt;</b> <br>This will display ALL errors, if any, right here with no formatting:<p> <html:errors bundle="ch12.HtmlErrors" /> <hr><br> <html:form action="HtmlErrors.do"> <table border="1" width="100%">   <tr>     <th align="center" width="35%">       Checking box will generate error     </th>     <th align="left" width="65%">      &lt;html:errors property="checkbox1" bundle="ch12.HtmlErrors" /&gt;     </th>   </tr>   <tr>     <td align="center">       <html:checkbox property="checkbox1"/>     </td>     <td align="left">       &nbsp;<html:errors property="checkbox1" bundle="ch12.HtmlErrors" />     </td>   </tr>   <tr>     <td align="right">       <html:submit>submit</html:submit>     </td>     <td align="left">       <html:reset>Reset</html:reset>       <html:cancel>Cancel</html:cancel>     </td>   </tr> </table> </html:form> </body> </html:html> 

Reviewing the form bean for this example is valuable to help demonstrate how the error tags are handled during form validation. Listing 12.9 is the form bean that goes with this JSP file ( HtmlErrorsForm.java ).

Listing 12.9 Form Bean That Corresponds with HtmlErrors.jsp ( HtmlErrorsForm.java )
 package ch12; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /**  * <p>Title: HtmlErrorsForm.java </p>  * <p>Description: Form Bean for the &lt;html:errors&gt; example</p>  * <p>Copyright: Copyright (c) 2002</p>  * @author Kevin Bedell & James Turner  * @version 1.0  *  */ public class HtmlErrorsForm extends ActionForm {   // Default bean constructor   public HtmlErrorsForm() { }   private boolean checkbox1;   public boolean getCheckbox1() { return this.checkbox1; }   public void setCheckbox1(boolean checkbox1) { this.checkbox1 = checkbox1; }      // --------------------------------------------------------- Public Methods     /**      * Reset all properties to their default values.      *      * @param mapping The mapping used to select this instance      * @param request The servlet request we are processing      */      public void reset(ActionMapping mapping, HttpServletRequest request) {          this.setCheckbox1(false);      }      /**       * Validate the properties posted in this request. If validation errors are       * found, return an <code>ActionErrors</code> object containing the errors.       * If no validation errors occur, return <code>null</code> or an empty       * <code>ActionErrors</code> object.       *       * @param mapping The current mapping (from struts-config.xml)       * @param request The servlet request object       * @return ActionErrors The ActionErrors object containing the errors.       */      public ActionErrors validate(ActionMapping mapping,                                   HttpServletRequest request) {          ActionErrors errors = new ActionErrors();          /*           * If the checkbox is checked, display error messages           */          if ( this.getCheckbox1() ) {              // First, a GLOBAL_ERROR message for the entire page.              errors.add(ActionErrors.GLOBAL_ERROR,                      new ActionError("ch12.global.error") );              // Also, display a specific error for this parameter              errors.add("checkbox1", new ActionError("ch12.checkbox.error"));          }          return errors;      } } 

Processing logic for this form bean is described in the following sections.

The <html:errors> Tag

The <html:errors> tag provides a method for managing the placement and formatting of text relating to errors encountered in form processing.

The <html:errors> tag, as part of the overall error processing framework that comes with Struts, provides a great deal of flexibility in how you process errors. The following are among its features:

  • Error text can be localized to the language of the user, based on the locale of the user's browser.

  • Error text messages can be taken from the primary ApplicationResources for the application or they can be defined in their own .properties file.

  • Errors can be identified as global, or relating to the form as a whole; they can also be mapped to a specific field on a form.

  • Error text can be parameterized using any information available to the form bean or Action class.

How Error Processing Works

To begin with, the <html:errors> tag only displays information if there are errors to display. If there are no errors to display, nothing is printed. So, to use this tag, you place it on your form where you want the errors to display and it does nothing until errors occur.

For example, there's an <html:errors> tag in the sample application that's used to display an error message depending on the status of the HTML check box element, checkbox1 . Here's the JSP code for the check box with the <html:errors> tag as well:

 <tr>   <td align="center">      <html:checkbox property="checkbox1"/>     </td>     <td align="left">      &nbsp; <html:errors property="checkbox1" bundle="ch12.HtmlErrors" />   </td> </tr> 

As you can see, both the <html:checkbox> and <html:errors> tags specify checkbox1 as the property they're tied to. For this example, an error condition is considered to have occurred if the check box is checked (this is enforced in the form bean, which is reviewed shortly).

Reviewing Figure 12.5, you can see the check box isn't checked and the error text isn't displayed. However, in Figure 12.6, the check box is checked and the error message is displayed.

The error messages are created in either the validate method of the form bean or in the Action class. In our sample application, they're created in the form bean using the following code:

 ActionErrors errors = new ActionErrors(); /*  * If the checkbox is checked, display error messages  */ if ( this.getCheckbox1() ) {        // First, a GLOBAL_ERROR message for the entire page.       errors.add(ActionErrors.GLOBAL_ERROR,                     new ActionError("ch12.global.error") );       // Also, display a specific error for this parameter       errors.add("checkbox1", new ActionError("ch12.checkbox.error")); } 

The same ActionError s object created here is passed back to the View component (the .jsp file) in a bean identified by the string constant Action.ERROR_KEY . This bean is stored on in the request scope.

The <html:errors> tag operates by first seeing whether this bean is available while the JSP file is being processed . If the bean is available, it's assumed that there are valid errors to display.

Specifying the Resource Bundle for the Error Text and Localizing the Text

Notice that the <html:errors> tag for checkbox1 specifies the attribute bundle="ch12.HtmlErrors . This directs the tag to take the error text from the message-resource named as ch12.HtmlErrors . The message-resource must be configured in the struts-config.xml file. The configuration for our example is

 <message-resources parameter="ch12.HtmlErrors" key="ch12.HtmlErrors" /> 

This tells us that the resource bundle being defined is in a file named HtmlErrors.properties , which is stored in the ch12 package somewhere on the Classpath .

The actual file from which these properties are loaded depends on the Locale of the user. They are the normal rules specified by the i18n features of the Java class java.util.ResourceBundle . For more information, please see the Javadoc for the class java.util.ResourceBundle or the Sun tutorial on i18n at http://java.sun.com/docs/books/tutorial/i18n/index.html.

Specifying Global Versus Field-Specific Error Messages

If no property attribute is specified in the <html:errors> tag, all the available error messages are printed. To print an individual error message, specify the error you want to print using the property attribute.

The ActionErrors.Global property is available to identify error messages that are global in nature; that is, messages that aren't tied to an individual property.

The sample application uses the following code in the form bean to add an ActionErrors.Global error:

 errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("ch12.global.error")); 

The JSP file then uses the following code to print only the ActionErrors.Global errors:

 <html:errors property="org.apache.struts.action.GLOBAL_ERROR"/> 

The string "org.apache.struts.action.GLOBAL_ERROR" is the actual value of the alias, ActionErrors.Global .

To print an error associated with an individual field, you simply specify the property name associated with the field both when you create the ActionError in the form bean and you create the <html:errors> tag in the JSP file.

Customizing Error Messages Using Parameters

Although the sample application doesn't demonstrate it, it's also possible to customize error messages using parameters. This is done when you create the ActionError entry in the form bean or Action class ”no modifications are required to the <html:errors> tag in the JSP file.

First, here's an error message and an ActionError being constructed with no parameter:

  • Specify the error message in the properties file:

     msg.without.parameter=Your entry is a BAD ENTRY! 
  • Create the ActionError with no parameter:

     errors.add("field1", new ActionError("msg.without.paramter")); 

Now, here's an error message and an ActionError being constructed with a parameter:

  • Specify the error message in the properties file:

     msg.with.parameter={0} is a BAD ENTRY! 
  • Create the ActionError with no parameter:

     errors.add("field1", new ActionError("msg.with.paramter", field1)); 

The second example passes the value of field1 as a parameter to customize the error message when it's displayed.

You can add additional parameters by using placeholders such as { 1 }, { 2 }, and so on, and then adding them as additional parameters to the ActionError constructor.



Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net