当我们表单类的属性个数和类型不能确定的时候,我们可以使用动态表单来解决。
动态表单和普通表单区别:
- 普通表单ActionForm,首先需要定义这样一个类,然后配置到Struts-config.xml中;
- 动态表单完全依赖反射机制创建,不需要定义表单类,直接在Struts-config.xml中配置即可
①在Struts-config.xml文件中配置动态表单
<form-beans>
<form-bean name="userForm" type="org.apache.struts.action.DynaActionForm">
<!-- 该表单的属性是配置出来的 -->
<form-property name="name" type="java.lang.String"></form-property>
<form-property name="password" type="java.lang.String"></form-property>
<form-property name="email" type="java.lang.String"></form-property>
</form-bean>
</form-beans>
②从动态表单中取出数据
public ActionForward register(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DynaActionForm userForm = (DynaActionForm) form;
// 从动态表单中取出数据
String name = (String) userForm.get("name");
String password = userForm.getString("password");
String email = userForm.getString("email");
System.out.println(name + " " + password + " " + email);
return mapping.findForward("ok");
}