基础页面:
![](https://i-blog.csdnimg.cn/blog_migrate/d57e4bb2d6833ba3e070ceb44d520540.png)
实现功能:根据复选框内容实现删除选中的数据。
前端页面:
设置复选框,并将复选框中的value值绑定为选中用户在数据库表中的 id
<form action="Servlet6" method="post" id="form">
<table border="1" align="center">
<tr class="tr1">
<td><input type="checkbox" id="all" onclick="checkAll()"></td>
<td>编号</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>籍贯</td>
<td>QQ</td>
<td>邮箱</td>
<td>操作</td>
</tr>
<c:forEach items="${pb.list}" var="l" varStatus="s">
<tr class="tr2">
<td><input type="checkbox" name="uId" value="${l.id}"></td>
<td>${s.count}</td>
<td>${l.name}</td>
<td>${l.sex}</td>
<td>${l.age}</td>
<td>${l.location}</td>
<td>${l.qq}</td>
<td>${l.email}</td>
<td><a href="${pageContext.request.contextPath}/Servlet5?UpdateId=${l.id}">修改</a>||<a href="${pageContext.request.contextPath}/Servlet4?id=${l.id}">删除</a></td>
</tr>
</c:forEach>
</table>
</form>
后端:
获取复选框中的id数组,实现逐个删除功能。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String[] uIds = request.getParameterValues("uId");
for (String s : uIds) {
try {
int id=Integer.parseInt(s);
dao.deleteById(id);
} catch (SQLException e) {
e.printStackTrace();
}
}
response.setStatus(302);
response.setHeader("location",request.getContextPath()+"/Servlet7");
}
操作数据库(根据id删除数据)
public static boolean deleteById(int id) throws SQLException {
Connection connection = JDBCUtils.getConnection();
Statement statement = connection.createStatement();
String sql="delete from user1 where id='"+id+"'";
if(statement.execute(sql)){
JDBCUtils.close(statement,connection);
return true;
}else {
JDBCUtils.close(statement, connection);
return false;
}
}