Thursday, January 17, 2013

DynaActionForm in struts with example.


      If you are writing Struts application, you are expected to write a FormBean for every page. But it's too tedious to write lot's of FormBeans with just getters and setters for the fields.
      You can avoid this by using DynaActionForm (Dynamic Form Beans) which are an extension of FormBeans that allow you to specify their fields inside the Struts configuration file itself instead creating concrete classes with getters and setters.
    For using this, you need to configure the form bean of DynaActionForm inside strust-config file. Do it this way :


<form-bean name="dynamicLoginForm" 
           type="org.apache.struts.action.DynaActionForm">
           <form-property name="userName" 
                          type="java.lang.String" 
                          initial="nils"></form-property>
           <form-property name="password" 
                          type="java.lang.String"></form-property>
</form-bean>

"name" attributes of "form-property" specify the field names and "type" specify the type of the field. you also can specify the initial value by "initial" attribute. And use dynamicLoginForm(name) of this form bean as value for name attribute of corresponding action just like normal FormBeans .


<action path="/login" 
            name="dynamicLoginForm">
</action>



    Now the values of fields of corresponding form on the webpage will be populated to the form which will be dynamically created. 
   So you need a way to access this values in Action class's execute() method. For that you need to use get() or getXXX() methods of DynaActionForm.
    Following snippet shows the way to access fields of DynaActionForm in execute() method of Action :

public ActionForward execute(ActionMapping mapping, 
                             ActionForm form,
                             HttpServletRequest request, 
                             HttpServletResponse response)
                      throws Exception {


     DynaActionForm theForm = (DynaActionForm)form;
     String userName = theForm.getString("userName");
     String password = (String)theForm.get("password");


}

Well, DynaActionForm is this much simple :)

No comments:

Post a Comment