DynaActionForm in Struts 1.2 with Example

In this tutorial, let us see how to use DynaActionForm in struts 1.2. DynaActionForm ( org.apache.struts.action.DynaActionForm) extends ActionForm class and  implements org.apache.commons.beanutils.DynaBean. This allows you to specify form properties at one configuration file which is the struts configuration file instead of creating a new ActionForm subclass and new getter/ setter methods for each properties defaults in the Struts configuration file.

To configure DynaActionForm, we have to make some entry in struts-config.xml as given below. Configure the properties (form fields)  and their types in struts-config.xml file.   We can add one or more <form-property> elements for each <form-bean> element. These properties are mapped with the Html form fields dynamically.

For example, consider a form that has properties (fields) of studentName, address, mark1, mark2, mark3.  The following code accepts above details and calculates total & average. Then acknowledgement is generated by printing Student name, Address , Total and Average.

Now we have to configure studentForm bean with various form-properties  in struts-config.xml and the studentForm is mapped to the  instance of  StudentAction class.  The complete struts-config.xml is given below.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
                               "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

	<!-- Form Beans -->

	<form-beans>

	<form-bean   name="studentForm"   type="org.apache.struts.action.DynaActionForm">  <!-- This is  DynaActionForm--> 

	     <form-property  name="method"    type="java.lang.String"  />

	     <form-property  name="studentName"    type="java.lang.String"   initial="Kumar"/>

	    <form-property name="address"   type="java.lang.String" />

	    <form-property name="mark1"   type="java.lang.Integer" initial="0" />

	    <form-property name="mark2"   type="java.lang.Integer" initial="0" />

	    <form-property name="mark3"   type="java.lang.Integer" initial="0" />

	    <form-property name="total"   type="java.lang.Integer" initial="0" />

	    <form-property name="avg"   type="java.lang.Double" initial="0" />

	</form-bean>

	</form-beans> 

	<!-- Action Mappings -->
	<action-mappings>
		  <action name="studentForm" path="/student" type="net.javaonline.struts.StudentAction" parameter="method">
     		<forward name="student" path="/Student.jsp"></forward>
     		<forward name="acknowledgementStudent" path="/StudentAcknowledgement.jsp"></forward>
   		</action>	

	</action-mappings>

</struts-config>
 

The following types are supported by DynaActionForm.

boolean and java.lang.Boolean, java.lang.BigInteger, java.lang.BigDecimal, byte and java.lang.Byte, char and java.lang.Character, java.lang.Class, java.sql.Date, java.sql.Time, java.sql.Timestamp, float and java.lang.Float, double and java.lang.Double, int and java.lang.Integer, long and java.lang.Long, short and java.lang.Short, java.lang.String 

The following dispatchAction code has two methods loadStudent &  studentProcess. loadStudent is used to load student form (Student.jsp) and studentProcess method is used to process the student details.

StudentAction.java


package net.javaonline.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

public class StudentAction extends DispatchAction {

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

			String strTarget="";

			ActionErrors errors = new ActionErrors();

			ActionForward forward = new ActionForward();

			try {

			strTarget = "student";

   			    } catch (Exception e) {  errors.add("name", new ActionError("id"));

					strTarget = "failure";

				        	   }

				   	if (!errors.isEmpty()) { 

						saveErrors(request, errors);

						strTarget = "failure";

					} else {

						strTarget = "student";

					}

			forward = mapping.findForward(strTarget);

			return (forward);

		}

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

		ActionErrors errors = new ActionErrors();

		ActionForward forward = new ActionForward();

		// return value

		try {

			DynaActionForm studentDynaForm = (DynaActionForm)form; 

		        String stName=(String)studentDynaForm.get("studentName");

			Integer mark1=(Integer)studentDynaForm.get("mark1");

			Integer mark2=(Integer)studentDynaForm.get("mark2");

			Integer mark3=(Integer)studentDynaForm.get("mark3");

			int total=mark1.intValue()+ mark2.intValue() + mark3.intValue();
			double avg=total/3.0;

			studentDynaForm.set("total", new Integer(total));

		        studentDynaForm.set("avg", new  Double (avg));

		} catch (Exception e) {

				errors.add("name", new ActionError("id"));

		}

		if (!errors.isEmpty()) {

			saveErrors(request, errors);

			System.out.println("error");

			forward = mapping.findForward("failure");

		} else {

				forward = mapping.findForward("acknowledgementStudent");

		}

		return (forward);

              }
}
// ******************** Action code Ends here

//  Student.jsp starts here to get Input


<!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 transitional//EN" "http://www.w3.org/tr/xhtml1/Dtd/xhtml1-transitional.dtd">
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<title>Student Form</title>

</head>
<body>
<html:errors />
<H1>Student Form</H1>

   <html:form  method="post" action="/student.do">

	<html:hidden property="method" value="processStudentMarks"/>

	<table border="1">

		<tr>

			<td>Student Name</td>

			<td ><html:text property="studentName"></html:text></td>

		</tr>

		<tr>

			<td>Address</td>

			<td><html:textarea property="address"></html:textarea></td>

		</tr>

		<tr>

			<td >Mark1</td>

			<td><html:text property="mark1"></html:text></td>

		</tr>

		<tr>

			<td>Mark2</td>

			<td><html:text property="mark2"></html:text></td>

		</tr>

		<tr>

			<td>Mark3</td>

			<td><html:text property="mark3"></html:text></td>

		</tr>

		<tr>

		<td colspan="2" align="center">	<input type="submit" value="Submit" > 	</td>

		</tr>

</table>

</html:form>

</body>
</html> 

AcknowledgeStudent.jsp starts here (Output)

<!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 transitional//EN" "http://www.w3.org/tr/xhtml1/Dtd/xhtml1-transitional.dtd">
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>

<title>Student Form Acknowledgement </title>

</head>
<body>
<html:errors />
<html:form method="get" action="/student.do">

<table>

		<tr>

			<td width="202">Student Name</td>

			<td width="270"><bean:write name="studentForm" property="studentName"/></td>

		</tr>

		<tr>

			<td width="202">Address</td>

			<td width="270"><bean:write name="studentForm" property="address"/></td>

		</tr>

		<tr>

			<td width="202">Total</td>

			<td width="270"><bean:write name="studentForm" property="total"/></td>

		</tr>

		<tr>

			<td width="202">Average</td>

			<td width="270"><bean:write name="studentForm" property="avg"/></td>

		</tr>

</table>

</html:form>

</body>
</html>

 

web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"     version="2.5">
	<display-name>Struts1Project</display-name>
  	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>
		<init-param>
			<param-name>debug</param-name>
			<param-value>2</param-value>
		</init-param>
		<init-param>
			<param-name>detail</param-name>
			<param-value>2</param-value>
		</init-param>
		<init-param>
			<param-name>validate</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

</web-app>

 

Run the application by calling

http://localhost:8080/Struts1Test/student.do?method=loadStudent

where Struts1Test is the project name.

Student Form:

Input Form:

dynaactionform

Output on Submit:

 

dynaactionform1

 

 

 

You may also like