在struts2中传值,一个表单里有两个方法,查询时候用了表单中的方法,删除时候必须通过节点获取表单,然后在给它赋值指定方法。
<%@ page language="java" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <title>测试checkbox</title> <script src="${dd}/js/jquery-1.6.1.min.js" type="text/javascript"></script> <script type="text/javascript"> jQuery(function($){ //全选 $("#qianxuan").click(function(){ $("input[name='checkbox']").attr("checked","true"); })//反选
$("#fanxuan").click(function(){ $("input[name='checkbox']").each(function(){ if($(this).attr("checked")) { $(this).removeAttr("checked"); } else { $(this).attr("checked","true"); } }) })}) function delete(){ var elements=document.testForm.elements; var counter=elements.length; for(i=0;i<counter;i++){ var element=elements[i]; if(element.checked == true){ document.forms.testForm.action="<%=path%>/action的名字"; document.forms.testForm.submit(); //上面红色的注释是通过节点获取表单给指定的方法,提交表单。 return true; } } alert("请选择一条记录进行操作"); return false;
}
</script> </head> <body> <s:form action="action的方法名" namespace="/test" method="post" id="testForm" name="testForm"> <s:iterator value="pageView.records" > < s:property value="name" /><input type="checkbox" name="checkbox" value="<s:property value="id" />"/>
</s:iterator> <input type="checkbox" name="checkbox" id="qianxuan" /> 全选 <input type="checkbox" name="checkbox2" id="fanxuan" /> 反选 </table> </s:form><input type="button" name="button4" id="button4" value="删除"
οnclick="delete();"/> </body> </html>后台:
public void delete(){
String[] checkBoxs = request.getParameterValues("checkbox"); String a = ""; for(int i = 0;i<checkBoxs.length;i++){ a += checkBoxs[i]+","; } String[] ids = a.split(","); Set<Integer> idslist = new HashSet<Integer>(); if (ids != null && ids.length > 0) { for (String id : ids) { idslist.add(new Integer(id)); } } //链接数据库dao ,把idslist传过去数据库操作有两种:1:直接放在in里;2:循环,每一次都执行一次sql,效率上很慢。
注意的是,若是sql操作的是实体类则stmt.createQuery,若是表的话createNativeQuery;
直接放在in里操作数据库
String sql ="update table set status ='-1' where id in(:ids)";
stmt.createNativeQuery(sql).setParameter("ids", idslist).executeUpdate();}