Monday, 11 April 2016

What is DynaActionForm and how to use it ?


A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.

Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward.
You need to make changes in two places :

In struts-config.xml
Change your to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm
<form-bean name="loginForm" type="org.apache.struts.action.DynaActionForm" >
    <form-property name="userName" type="java.lang.String" />
    <form-property name="password" type="java.lang.String" />
</form-bean>

In your Action subclass that uses your form bean
  • Import org.apache.struts.action.DynaActionForm
  • Downcast the ActionForm parameter in execute() to a DynaActionForm
  • Access the form fields with get("field") rather than getField()

Example
import org.apache.struts.action.DynaActionForm;
public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form
    HttpServletRequest request, HttpServletResponse response) 
    throws Exception {       
      DynaActionForm loginForm = (DynaActionForm) form;
      ActionMessages errors = new ActionMessages();       
        
      if (((String) loginForm.get("userName")).equals("")) {
         errors.add("userName", 
                    new ActionMessage("error.userName.required"));
      }
      if (((String) loginForm.get("password")).equals("")) {
         errors.add("password", 
                    new ActionMessage("error.password.required"));
        }
        // other processing here
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.