1.创建一个html页面,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>批量删除</title>
<!--jq在线路径,需要联网-->
<script src= "http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
/*复选框的统一,不需要理解 拿去用就行*/
function allCheck(all){
//得到所有复选框的节点
var arr=document.getElementsByTagName("input");
for(var i=0;i<arr.length;i++){
if(arr[i].type=="checkbox"){
arr[i].checked=all.checked;
}
}
}
function myClick(){
var arr=document.getElementsByName("zi");
var b=true;
for(var i=0;i<arr.length;i++){
if(!arr[i].checked){
b=false;
break;
}
}
document.getElementById("fu").checked = b;
}
/*上面的js代码拿着用就行,下面的需要改参数*/
//页面加载完成后执行
$(function (){
//调用刷新数据的方法
init("/CommodityController?requestType=dataList");
})
function init(url){
$.ajax({
type:"post",
url:url,
dataType:"json",
success:function (data) {
$("#tb").empty();//将之前的数据清空
for(var i=0;i<data.length;i++){
var tr='<tr>' +
' <td>'+data[i].id+'</td>' +
' <td>'+data[i].name+'</td>' +
' <td>'+data[i].price+'</td>' +
' <td>'+data[i].stock+'</td>' +
' <td>' +
' <input name="zi" value="'+data[i].id+'" onclick="myClick()" type="checkbox"/>' +
' </td>' +
' </tr>'
$("#tb").append(tr);
}
}
})
}
//点击批量删除按钮
function DatchDelete(){
//定义一个数组用来存储商品的id
var chk_value =[];
//循环个数组赋值
$('input[name="zi"]:checked').each(function(){
chk_value.push($(this).val());
});
if(chk_value.length==0){//判断数组里是否有商品
alert("你还没有选择任何内容!");
}else{//如果有则向后台发送ajax请求//将请求类型和数组传递到后台处理
$.ajax({
url:"/CommodityController?requestType=batchDelete&arr="+chk_value,
type:"post",
success:function (zt) {
alert("删除成功!");
//为了防止数据不刷新再调用一次更新数据的请求
init("/CommodityController?requestType=dataList");
}
})
}
}
</script>
</head>
<body>
<input type="button" value="批量删除" onclick="DatchDelete()">
<table height="200px" width="400px" border="1px" cellpadding="0" cellspacing="0" style="text-align: center;">
<tr>
<th>商品编号</th><th>商品名称</th>
<th>商品价格</th><th>商品库存</th>
<th>
全选
<input id="fu" onclick="allCheck(this)" type="checkbox"/>
</th>
</tr>
<tbody id="tb">
</tbody>
</table>
</body>
</html>
2.建一个实体类用来存储数据库数据,代码如下:
package com.gy.pojo;
public class Commodity {
private int id ;
private String name ;
private double price ;
private int stock ;
public Commodity() {
}
public Commodity(int id, String name, double price, int stock) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
3.建立数据库连接,代码如下:
DBUtil数据连接类,不会建db.properties文档的下面文档有教程:
package com.gy.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtil {
private static String drivername;
private static String url;
private static String username;
private static String pwd;
//静态块代码
static {
try {
InputStream is=DBUtil.class.getClassLoader().getResourceAsStream("com/gy/util/db.properties");
//属性集的类
Properties p=new Properties();
p.load(is);
drivername=p.getProperty("driver");//数据库连接池相当于driver=com.mysql.cj.jdbc.Driver
url=p.getProperty("url");//相当于url=jdbc:mysql://127.0.0.1:3306/Book?characterEncoding=UTF-8&&serverTimezone=UTC这个
username=p.getProperty("user");//用户名
pwd=p.getProperty("password");//数据库连接密码
Class.forName(drivername);
}catch (Exception e){
e.printStackTrace();
System.out.println("数据库连接异常!");
}
}
//封装连接数据库
public static Connection getConn(){
try {
return DriverManager.getConnection(url,username,pwd);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
//封装关闭连接
public static void closeConn(Connection conn, PreparedStatement ps, ResultSet rs){
if(rs!=null){
try {
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
建一个db.properties文档用来存储数据的连接信息:
driver=com.mysql.cj.jdbc.Driver//注意这里需要看jar包类型来写,不会的百度
url=jdbc:mysql://127.0.0.1:3306/数据库名?characterEncoding=UTF-8&&serverTimezone=UTC
user=root//用户名
password=12345678//密码
封装好的增,删,改代码拿着用就行:
package com.gy.dao;
import com.gy.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class BaseDao {
private Connection conn;
private PreparedStatement ps;
public int toUpdate(String sql,Object[] obs){
int a=0;
conn= DBUtil.getConn();
try{
ps=conn.prepareStatement(sql);
if(obs!=null&&obs.length>0){
for (int i=0;i<obs.length;i++){
ps.setObject(i+1,obs[i]);
}
}
a=ps.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtil.closeConn(conn,ps,null);
}
return a;
}
}
3.编写数据持久层:
建一个接口:
package com.gy.dao;
import com.gy.pojo.Commodity;
import java.util.List;
public interface CommodityDao{
//所有数据
List<Commodity> DataList();
//批量删除
int BatchDelete(int[] id);
}
实现上面的接口里,面是对数据库的删除和查询:
package com.gy.dao;
import com.gy.pojo.Commodity;
import com.gy.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class CommodityDaoImpl extends BaseDao implements CommodityDao{
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
@Override
public List<Commodity> DataList() {
try {
List<Commodity> list=new ArrayList<>();
conn= DBUtil.getConn();
String sql="select * from commodity";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while (rs.next()){
Commodity commodity=new Commodity();
commodity.setId(rs.getInt(1));
commodity.setName(rs.getString(2));
commodity.setPrice(rs.getDouble(3));
commodity.setStock(rs.getInt(4));
list.add(commodity);
}
return list;
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtil.closeConn(conn,ps,rs);
}
return null;
}
@Override
public int BatchDelete(int[] id) {
String sql="DELETE from commodity where id in (";//由于是批量删除所有我们有用in来做删除,不懂重新学一遍MySql
for(int i=0;i<id.length;i++){
if(id.length==1){//判断用户是单个删除还是批量删除如果是单个则不加"," 然后直接结束循环
sql+=id[i];
break;
}
sql+=id[i];
if(i==id.length-1){//判断该数是不是最后一个,如果是则不加","号,然后直接结束循环
break;
}else{//否则加上",",不懂的自己断点看!
sql+=",";
}
}
sql+=")";//循环结束后集合给in结尾
return toUpdate(sql,null);//这个是我封装我的,增,删,改的方法,等会在后面给你们
}
}
4.编写表示层:
新建一个servlet类:
package com.gy.controller;
import com.alibaba.fastjson.JSON;
import com.gy.dao.CommodityDao;
import com.gy.dao.CommodityDaoImpl;
import com.gy.pojo.Commodity;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/CommodityController")
public class CommodityController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestType=request.getParameter("requestType");
//数据显示的请求类型
if(requestType.equals("dataList")){
DataList(request,response);
}
//批量删除请求类型
if(requestType.equals("batchDelete")){
BatchDelete(request,response);
}
}
public void BatchDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
//接受前端传过来的商品id
String arr=request.getParameter("arr");//前端穿过来的是字符串类型
//将前端穿过的字符串进行截取 不知道的可以将arr输出在控制台 split函数是截取的意思不懂得百度
String[] id=arr.split(",");
//定义一个int类型的到数组
int[] sid=new int[id.length];
//循环将 id 数组的值赋值给 sid 数组
for (int i=0;i<id.length;i++){
sid[i]=Integer.parseInt(id[i]);
}
CommodityDao dao=new CommodityDaoImpl();
int zt=dao.BatchDelete(sid);//调用实现类的批量删除方法
PrintWriter pw=response.getWriter();
pw.println(zt);//是否删除告知给前端页面
DataList(request,response);//调用DataList方法让前端可以刷新数据
pw.close();
}
private void DataList(HttpServletRequest request, HttpServletResponse response) throws IOException {
/**
* 处理传输乱码
*/
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
CommodityDao dao=new CommodityDaoImpl();
List<Commodity> dataList=dao.DataList();//调用实体类的DataList方法
String json= JSON.toJSONString(dataList);//将list类型的数据转换为json,传给前端页面
PrintWriter pw=response.getWriter();
pw.println(json);//将这个json数据传递到前端
pw.close();
}
}
5.我的数据库
CREATE TABLE `commodity` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
`price` double(10,2) DEFAULT NULL,
`stock` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=114 DEFAULT CHARSET=utf8mb3 COLLATE=utf8_croatian_ci;
INSERT INTO `commodity` VALUES (110, '旺仔大礼包', 99.90, 99);
INSERT INTO `commodity` VALUES (111, '泡芙', 5.00, 89);
INSERT INTO `commodity` VALUES (112, '旺仔牛奶', 4.00, 100);
INSERT INTO `commodity` VALUES (113, '老坛酸菜面', 2.50, 99);
6.最后给大家看一下我的项目结构:
觉得对你有用就点个赞吧!有需要模糊查询,分页的d一下