Passing Data with Form Beans

 <  Day Day Up  >  

Until now, the user 's interaction with the chip buying application has been limited. Users have a choice of three different chip sets they could buy, but what if they want to buy chips in a different amount than 100, 500, or 1,000? Obviously you can't add a link for every possible combination of chips that can be bought. Instead, you can add a form and pass the data by using Form beans . Form beans are used to encapsulate data from a form and give developers an easy way to gain access to form values.

Creating a Form Bean

To add a Form bean to an existing action, go to Action View and click the Add button next to Form Beans in the Data Palette. Figure 4.8 shows the New Form Bean dialog box for configuring the properties of a Form bean.

Figure 4.8. Adding a Form bean to a Page Flow.

graphics/04fig08.gif

In the New Form Bean dialog box, add all the form elements the form will have. Notice that Figure 4.8 shows two elements: one for the confirmation number of the guest and the other for the amount of chips to prepurchase. Listing 4.3 shows the code Workshop produces for the Form bean. Note that the generated Form bean class is an inner class of the Controller.

Listing 4.3. The buyChipsBean Form Bean Generated by Workshop
 public class Controller extends PageFlowController {  ...  public static class BuyChipsBean extends FormData     {         private int chipAmt;         private String confirmationNumber;         public void setConfirmationNumber(String confirmationNumber)         {             this.confirmationNumber = confirmationNumber;         }         public String getConfirmationNumber()         {             return this.confirmationNumber;         }         public void setChipAmt(int chipAmt)         {             this.chipAmt = chipAmt;         }         public int getChipAmt()         {             return this.chipAmt;         }     } } 

All that's left is to update the purchaseChips action to accept the Form bean. To do this, simply add a parameter to the method signature, as shown here:

 protected Forward purchaseChips(BuyChipsBean form) 

Now just use the form variable as you would any other variable to manipulate the values in the Form bean.

Using Form Beans

Now it's time to add the form to the buyChips.jsp file instead of using the links you had before. To add a form to buyChips.jsp , drag a < netui :form> tag onto the JSP where you want the form displayed. The Form Wizard - Choose Action dialog box shown in Figure 4.9 opens, prompting you for the action the form will call.

Figure 4.9. Associating an action with a Form bean.

graphics/04fig09.gif

Figure 4.10 shows the next part of the Form Wizard, where you decide which fields from the Form bean should be in the HTML form on a JSP page.

Figure 4.10. Selecting the fields for a form.

graphics/04fig10.gif

After selecting the fields, choose which type of form elements should represent the attributes (see Figure 4.11). Click Create, and Workshop builds the form code for you, as shown in Listing 4.4.

Listing 4.4. The buyChips.jsp Using a Form Bean
 <%@ page language="java" contentType="text/html;charset=UTF-8"%> <%@ taglib uri="netui-tags-databinding.tld" prefix="netui-data"%> <%@ taglib uri="netui-tags-html.tld" prefix="netui"%> <%@ taglib uri="netui-tags-template.tld" prefix="netui-template"%> <netui:html>     <head>         <title>             Prepay for Chips         </title>     </head>     <body>         <p>         We offer different amounts of chips to buy.        The cost will be added to your room bill and will be waiting for you         when you arrive.         <br>         <netui:form action="purchaseChips" focus="">             <table>                 <tr>                     <td><netui:label value="Chip Amount:"></netui:label></td>                     <td>                         <netui:textBox dataSource="{actionForm.chipAmt}">                         </netui:textBox>                     </td>                 </tr>                 <tr>                     <td><netui:label value="Confirmation Number:">                         </netui:label>                     </td>                     <td>                     <netui:textBox dataSource="{actionForm.confirmationNumber}">                     </netui:textBox>                     </td>                 </tr>             </table>             <netui:button value="purchaseChips"></netui:button>         </netui:form>         </p>     </body> </netui:html> 
Figure 4.11. Selecting the field types for a form.

graphics/04fig11.gif

To link the form to the purchaseChips action, use the <netui:form> tag and specify the action attribute as purchaseChips . To associate the chipAmt Form bean attribute with the form element, set the dataSource attribute of <netui:textbox> equal to the XScript expression {actionForm.chipAmt} .

Now that the buyChips.jsp has been updated, you need to fix the Controller to handle those values. Previously, you updated the purchaseChips action to accept the buyChipsBean . Listing 4.5 shows how to access those values.

Listing 4.5. The purchaseChips Action Using the Form Bean
 /**      * @jpf:action      * @jpf:forward name="confirmed" path="confirmation.jsp"      * @jpf:forward name="highRoller" path="highRoller.jsp"      *      */     protected Forward purchaseChips(BuyChipsBean form)     {         amt = form.getChipAmt();         String confirmNum = form.getConfirmationNumber();         if (amt > 1000)             return new Forward("highRoller");         else             return new Forward("confirmed");     } 

In the preceding code, you're storing the amount of chips bought in the previously created Page Flow variable amt . Also, the test condition was updated to determine whether someone is considered a high roller . Figure 4.12 shows the updated results of the BuyChips application.

Figure 4.12. The BuyChips application using Form beans.

graphics/04fig12.gif

Form Bean Validation

Currently, this application doesn't check values that are entered. What if the application restricts the confirmation number to only four digits? There's a good possibility that entering too many or too few numbers could break the application. The solution is validating the data in the Form bean. Validation consists of five tasks :

  • Create error messages.

  • Add a messages-resources tag.

  • Add a validation-error-page tag.

  • Display errors in the JSP.

  • Add a validate method.

Creating an Error Message

To avoid coding error messages directly in the JSP or the Controller, you code them in a properties file located in the WEB-INF/classes directory or some subdirectory. The major advantage of this practice is that the same message can be used for many pages. If the error message needs to change for any reason, you simply update it in one place instead of several places. The properties file also contains the message formatting. Often, this file is named Messages.properties . In this chapter's example, the Messages.properties file is stored in the validation directory under WEB-INF/classes . The file looks like this:

 invalidConfirmation=All Confirmation numbers are 4 digits. error.prefix=<font color="Red"> error.suffix=</font> 

The error.prefix and error.suffix allow formatting information to be displayed for the error message.

Add a <message-resource> Tag

Now that you have an error message to display, you need to make the application take advantage of it. The next step is adding a <message-resource> tag to the Controller that defines which properties file is used for this Controller. The following lines show the code to do this:

 /** * @jpf:controller *@jpf:message-resources resources="Messages" */ public class Controller extends PageFlowController { 
Add a <validation-error-page> Tag

The <validation-error-page> tag is used in the Controller to signify which actions use validation and which page the Controller should send the application to if there is an error. In this example, the action is purchaseChips , and you want the application to return to buyChips.jsp . To do this, use the following code:

 /**      * @jpf:action validation-error-page="buyChips.jsp"      * @jpf:forward name="confirmed" path="confirmation.jsp"      * @jpf:forward name="highRoller" path="highRoller.jsp"      *      */     protected Forward purchaseChips(BuyChipsBean form)     { 
Display the Errors in a JSP

In the buyChips.jsp , you need to edit the form to accept potential errors caused by validation. To do this, use the <netui:error> tag and supply a value that's used in the validate method of the Controller. In this example, you supply confirmNumber as the value of the <netui:error> tag. Listing 4.6 shows the new buyChips.jsp .

Listing 4.6. Adding Error Handling in buyChips.jsp
 <netui:form action="purchaseChips" focus="">     <table>         <tr>             <td><netui:label value="Chip Amount:"></netui:label></td>             <td>  <netui:textBox dataSource="{actionForm.chipAmt}">   </netui:textBox>  </td>         </tr>         <tr>  <td><netui:label value="Confirmation Number:">   </netui:label></td>  <td>  <netui:textBox dataSource="{actionForm.confirmationNumber}">   </netui:textBox>  </td>             <td><netui:error value="confirmNumber"/></td>         </tr>     </table>     <netui:button value="purchaseChips"></netui:button> </netui:form> 
Add a validate Method

The validate method actually performs the form validation and is added to the Form bean class ”in this example, the BuyChipsBean class. The signature of this method must look exactly like this:

 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) 

In the validate method, you create the ActionErrors object. Every time there is an invalid field, you add another error by using the add() method. Listing 4.7 shows a completed validate method.

Listing 4.7. Validating a Form Within the Form Bean
 public static class BuyChipsBean extends FormData { private int chipAmt;      private String confirmationNumber;         public ActionErrors validate                (ActionMapping mapping, HttpServletRequest request)         {             ActionErrors errors = new ActionErrors();             if (confirmationNumber.length() != 4)                 errors.add                 ("confirmNumber", new ActionError("invalidConfirmation"));             return errors;    . . . } 

A key point to remember is that your validate method has access to all the member attributes of your Form bean's class. Figure 4.13 shows the results of validation in the form.

Figure 4.13. Validation in a Form bean.

graphics/04fig13.gif

Now that you've learned about all the pieces for this application, it's time to see how all the pieces work together. Figure 4.14 shows all the participants in validation and how they are involved.

Figure 4.14. Validation in a nutshell ”a rather large nutshell .

graphics/04fig14.gif

At first glance, this diagram seems overwhelming, so the following discussion breaks it into separate pieces. Remember, you must have a Message.properties file; in Figure 4.14, it's displayed in the upper-left corner. To use the Message.properties file, the Controller has to define the properties file it uses; this is what the @jpf:message-resources tag is used for. Now that the Controller is set up to use messages, you set up the action for specifying a page if there's a validation problem. In this case, it happens to be the buyChips.jsp , which also calls the purchaseChips action. Before the action is performed, the validate method of the Form bean is executed. Here it determines which error message is displayed as well as where on the JSP it should be displayed.

 <  Day Day Up  >  


BEA WebLogic Workshop 8.1 Kick Start
BEA WebLogic Workshop 8.1 Kick Start: Simplifying Java Web Applications and J2EE
ISBN: 0672326221
EAN: 2147483647
Year: 2004
Pages: 138

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