JavaWeb前后端分离使用ajax实现批量删除和显示数据

1.创建一个html页面,代码如下:

JavaWeb前后端分离使用ajax实现批量删除和显示数据_第1张图片



    
        
        批量删除

        
        

        
    
    
        
        
商品编号商品名称 商品价格商品库存 全选

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

3.编写数据持久层:

建一个接口:

package com.gy.dao;

import com.gy.pojo.Commodity;

import java.util.List;

public interface CommodityDao{
    //所有数据
    List 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 DataList() {
        try {
            List 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

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 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.最后给大家看一下我的项目结构:JavaWeb前后端分离使用ajax实现批量删除和显示数据_第2张图片

觉得对你有用就点个赞吧!有需要模糊查询,分页的d一下 

你可能感兴趣的:(java)