今天有人問前臺表單form動態生成,后臺使用DynaActionForm怎么用,說了他沒懂,就寫了個例子。
Action配置
<action
attribute="testMappingForm"
input="/jsp"
name="testMappingForm"
path="/testMapping"
scope="request"
type="com.modo.struts.action.TestMappingAction" />
attribute="testMappingForm"
input="/jsp"
name="testMappingForm"
path="/testMapping"
scope="request"
type="com.modo.struts.action.TestMappingAction" />
ActionForm配置
<form-bean name="testMappingForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="fnames" type="java.util.HashMap"></form-property>
</form-bean>
<form-property name="fnames" type="java.util.HashMap"></form-property>
</form-bean>
請注意name屬性,這個屬性后面要用到。
然后是頁面index.jsp,這里只模擬動態
<html:form action="/testMapping.do" method="post">
<%
for(int i=0;i<5;i++){
%>
<html:text property="<%="fnames(name_"+i+")"%>" value="<%="gangye_"+i%>"></html:text><br>
<%}%>
<br>
<html:submit value="Submit Form
" />
</html:form>
<%
for(int i=0;i<5;i++){
%>
<html:text property="<%="fnames(name_"+i+")"%>" value="<%="gangye_"+i%>"></html:text><br>
<%}%>
<br>
<html:submit value="Submit Form

</html:form>
請注意html:text的property標簽。
index.jsp效果如下
后臺Action
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
HashMap hm=(HashMap)((DynaActionForm)form).get("fnames");
Iterator it = hm.entrySet().iterator();
Map.Entry entry = null;
while(it.hasNext()){
entry = (Map.Entry)it.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
return null;
}
HttpServletResponse response) {
HashMap hm=(HashMap)((DynaActionForm)form).get("fnames");
Iterator it = hm.entrySet().iterator();
Map.Entry entry = null;
while(it.hasNext()){
entry = (Map.Entry)it.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
return null;
}
輸出表單項





