Monday, January 10, 2011

DynaActionForm Example

DynaActionForm is specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of 
properties, without requiring the developer to create a Java class for each type of form bean.
DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. 
So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

For Example: You have a EmpForm and you don't want a java class (EmpForm).
EmpForm has propertis firstName, lastName, country.

In the struts-config.xml file , declare the form bean:
<form-bean name="EmpForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="firstName" type="java.lang.String"/>
<form-property name="lastName" type="java.lang.String"/>
<form-property name="country" type="java.lang.String" />
</form-bean>

Add action mapping in the struts-config.xml file:
<action path="/saveEmp" type="com.techfaq.action.EmpSaveAction" name="EmpForm" scope="request" validate="true" input="/pages/empform.jsp">
<forward name="success" path="/jsp/success.jsp"/>
<forward name="failure" path="/jsp/error.jsp" />
</action>

In the Action class.
public class EmpSaveAction extends Action {
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
DynaActionForm empForm = (DynaActionForm)form;
// this is the way you can retrive the value which is set in the JSP Page
String firstName = (String)empForm.get("firstName");
String lastName = (String)empForm.get("lastName");
return mapping.findForward("success");
}
}

In the JSP page
<html:text property="firstName" size="30" maxlength="30"/>
<html:text property="lastName" size="30" maxlength="30"/>

No comments:

Post a Comment