解决思路
- 在jsp中,使用js或者jquery实现复选框多选
- 在Controller中接受数组
- 在Service遍历数组,多次调用DAO中的deleteById()方法
- 在DAO编写deleteById()
代码实现:
Show.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function checkall(){
var goodsIdALL = document.getElementById("goodsIdALL");
var goodsIds = document.getElementsByName("goodsIds");
for(var i=0;i<goodsIds.length;i++){
goodsIds[i].checked = goodsIdALL.checked;
}
}
//多项删除方法,提交表单
function todels(){
if(confirm("是否确认删除?")){
document.delForm.submit();
}
}
function todel(id){
if(confirm("是否确认删除?")){
location.href="${pageContext.request.contextPath}/delById.do?goodsId="+id;
}
}
</script>
</head>
<body>
<a href="${pageContext.request.contextPath }/toSave.do">新增</a>
//表单提交给删除多项控制器
<form action="${pageContext.request.contextPath }/delAll.do" method="post" id="delForm" name="delForm">
<table width="80%" border="1px" cellpadding="1" cellspacing="0">
<Tr>
<td><input type="checkbox" name="goodsIdALL" id="goodsIdALL" onclick="checkall()">
//多项删除,调用todels()方法
<a href="javascript:todels()">删除</a></td>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>数量</td>
<td>类型</td>
<td>操作</td>
</Tr>
<c:forEach items="${requestScope.goodsList }" var="goods">
<Tr>
<td><input type="checkbox" name="goodsIds" value="${goods.goodsId }"></td>
<td>${goods.goodsId }</td>
<td>${goods.goodsName }</td>
<td>${goods.goodsPrice }</td>
<td>${goods.goodsNum }</td>
<td>${goods.goodsType.typeName }</td>
<td>
//单条记录删除
<A href="javascript:todel(${goods.goodsId })">删除</A>
<A href="${pageContext.request.contextPath }/toUpdate.do?goodsId=${goods.goodsId}">修改</A>
</td>
</Tr>
</c:forEach>
</table>
</form>
</body>
</html>
Controller
//获取id数组
String[] goodsIds = request.getParameterValues("goodsIds");
goodsService.deleteAll(goodsIds);
Service
for(String id:ids){
this.goodsDao.deleteById(Integer.parseInt(id));
}
DAO
String sql ="delete from goods where goods_id=?";
Connection conn = JdbucUtils.getConnection();
PrepareSatament ps = coon.prepareStatement(sql);
ResultSet rs = ps.execteQuery();