Recipe5.2.Setting DynaActionForm Initial Values


Recipe 5.2. Setting DynaActionForm Initial Values

Problem

You need to initialize the properties in a dynamic action form declared in the struts-config.xml file.

Solution

Specify an initial value for a property of a DynaActionForm using the initial attribute of the form-property element.

<form-bean name="MyForm" type="org.apache.struts.action.DynaActionForm">   <form-property name="firstName" type="java.lang.String"               initial="George"/>   <form-property name="lastName" type="java.lang.String"               initial="Burdell"/>   <form-property name="javaCoder" type="java.lang.Boolean"               initial="true"/>   <form-property name="friend" type="java.lang.String[]"                  size="3"                initial="Larry,Moe,Curly"/> </form-bean>

Discussion

DynaActionForms simplify your life as a Struts developer. There is no Java code to write, and when requirements change and you must add fields to a form, you need only change some XML and the Actions that use the form. When working with these forms, a common question that comes up is how to populate the form with initial values. The Solution shows how this can be done using the initial attribute of the form-property element. This attribute specifies a default value for a property. The property is set to this value when the form is created or when the initialize( ) method is called on the form. The time of creation depends on the scope of the form. If the scope is "request," a new form is created for each new request that uses the form. For session scope, the form is created when it can't be found in the current HTTP session.

Beware the Session-Scoped Form

Be careful of overusing session-scoped forms. Using forms in session scope is acceptable; the use of the session can make development of your web application a lot easier. However, you'll run into two common problems when the form is not removed from the session after use.

The first problem affects usability. When a form is not removed after its usage is complete, JSP pages that use that form will display old data from the form instead of displaying a properly initialized new form.

The second problem is more serious. If the application needs to support many users, using session-scoped forms without proper removal can impact the performance of the application and increase the required memory footprint.

The rule of thumb is to declare forms to use request scope. Then, change the scope to session only if needed. When an action is done with a form and it is no longer part of the workflow, the form should be removed from the session.


The initial value, like any other XML attribute value, is specified as a double-quoted text string. Since most form properties should be Strings, specifying an initial value is straightforward. Care must be taken if the initial value contains embedded quotes or other special characters, though. These characters should be escaped by preceding the character with a leading backslash:

<form-property name="quotation"              initial="John Dunne wrote \"No man is an island\""/>

If the property type is java.lang.Boolean, then the initial value should be set to TRue or false, ignoring case. Boolean properties are false by default.

If the property is an array type, the value for the initial attribute can represent multiple values. String values are listed as comma or space-separated values. If the Strings contain spaces, then wrap the value in single quotes. If the value contains an embedded single or double quotation mark or other character that may cause parsing problems, then escape the character by preceding it with a backslash. If an array value should be blank, you use the empty String (""). Here are some examples of acceptable syntax for the initial value of a String array property, and the equivalent String array literal:

initial="Larry,Moe,Curly"   {"Larry","Moe","Curly"} initial="Fine,Horward"   {"Fine","Howard"} initial="Larry Moe Curly"   {"Larry","Moe","Curly"} initial="'Larry','','Curly'"   {"Larry","","Curly"} initial="'O\'Reilly','Struts','Cook Book'"   {"O'Reilly","Struts","Cook book"}

The size attribute of the form-property element applies to array-based properties. This attribute sets the number of elements in the array. If the initial value specifies more elements than the size attribute, the size of the array is set to the larger valuei.e., the number of initial values.

In a beta version of Struts 1.1, calling reset( ) on a DynaActionForm set the property values to the initial values. With Struts 1.1 final, this behavior was aligned with that of conventional action formsi.e., the form's initial values are only set when the form is created. The initialize( ) method, however, will reset the property values to their initial values. If you need the reset( ) method to work like Struts 1.1 beta, you can create a subclass of DynaActionForm that overrides the reset( ) method. Example 5-2 shows a DynaActionForm subclass that reinitializes the values on form reset.

Example 5-2. DynaActionForm extension for resetting properties
package com.oreilly.strutsckbk.ch05; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; public class ResettingDynaActionForm extends DynaActionForm {     public void reset(ActionMapping mapping, HttpServletRequest request) {         initialize(mapping);     } }

You can specify this class as the value of the type attribute of the form-bean element.

<form-bean name="MyFooForm"            type="com.oreilly.strutsckbk.ch05.ResettingDynaActionForm">   <form-property name="foo" type="java.lang.String"               initial="bar"/> </form-bean>

The primary disadvantage of the initial attribute is that it forces you to hardcode the values. In many cases, this meets requirements; at other times, you want the values to be determined dynamically at runtime. In this situation, the DynaActionForm can be populated from Java code, typically in the Action preceding a forward to the JSP page that displays the form. The DynaActionForm values can be set using the DynaActionForm.set( ) methods or the introspection utilities provided by the PropertyUtils class in Jakarta Commons BeanUtils package. Example 5-3 shows both of these techniques.

Example 5-3. Populating a DynaActionForm
package com.oreilly.strutsckbk.ch05; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; public class ViewFormAction extends Action {     public ActionForward execute(ActionMapping mapping,       ActionForm form,       HttpServletRequest request,       HttpServletResponse response) throws Exception {                  DynaActionForm myForm = (DynaActionForm) form;         PropertyUtils.setSimpleProperty(myForm, "firstName", "Bill");         myForm.set("lastName", "Siggelkow");                      return mapping.findForward("success");     } }

See Also

Recipe 5.5 shows how to create and use a dynamic form that allows for the properties to be determined completely at runtime. Recipe 5.6 shows additional solutions for populating forms in an Action.

The Struts User's Guide discusses dynamic action forms in the section http://struts.apache.org/userGuide/building_controller.html#dyna_action_form_classes.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

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