JSP
<form id = "delForm" method = "post">
<logic:iterate id="bean" name="beanList" >
<tr>
<td><input type = "checkbox" name = "ids" value = '<bean:write name = "bean" property = "id"/>'></td>
<td>.....</td>
</tr>
</logic:iterate>
<input type = "button" value = "全选" onclick = "for (var i = 0; i < delForm.questionIds.length; i ++){delForm.questionIds[i].checked = true;}"/>
<input type = "button" value = "反选" onclick = "for (var i = 0; i < delForm.questionIds.length; i ++){delForm.questionIds[i].checked = false;}"/>
<input type = "button" value = "删除选中" onclick = "if(confirm('真的要删除选中内容?'))delForm.submit()"/>
</form>
<logic:iterate id="bean" name="beanList" >
<tr>
<td><input type = "checkbox" name = "ids" value = '<bean:write name = "bean" property = "id"/>'></td>
<td>.....</td>
</tr>
</logic:iterate>
<input type = "button" value = "全选" onclick = "for (var i = 0; i < delForm.questionIds.length; i ++){delForm.questionIds[i].checked = true;}"/>
<input type = "button" value = "反选" onclick = "for (var i = 0; i < delForm.questionIds.length; i ++){delForm.questionIds[i].checked = false;}"/>
<input type = "button" value = "删除选中" onclick = "if(confirm('真的要删除选中内容?'))delForm.submit()"/>
</form>
FormBean( 我使用的是DynaActionForm,所以在struts-config.xml中配置)
<form-bean name="testingForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="id" type="java.lang.String"/>
<form-property name="ids" type="java.lang.String[]"/>
........
</form-bean>
Action
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// 获取操作名
DynaActionForm dyna = (DynaActionForm) form;
// ids数组是所有被选中记录的id值
String[] ids = (String[]) dyna.get("ids");
// 调用相应dao方法,完成删除所有指定id操作
return mapping.findForward(".....");
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// 获取操作名
DynaActionForm dyna = (DynaActionForm) form;
// ids数组是所有被选中记录的id值
String[] ids = (String[]) dyna.get("ids");
// 调用相应dao方法,完成删除所有指定id操作
return mapping.findForward(".....");
}
说明
关键就在于FormBean的设置,也就是那个数组ids,一般的实现方法会在客户端首先遍历一遍所有被选中的checkbox,然后使用js拼装字符串,传给action,在后台解析该字符串得到所有被选中的指定的id,这个方法没有什么不妥,不过使用struts会更简单些,而这里使用一个FormBean的数组属性来对应页面中的 checkbox DHTML数组对象,struts替我们完成了遍历所有checkbox,并找出所有被选中checkbox的value,是不是更简单呢?还有一个需要搞明白的就是html:iterate所用的Bean和执行批量删除操作的FormBean是两码事,我开始就差点搞混淆了。