mysql+servlet+ajax实现批量删除功能

1.数据连接池采用c3p0,配置如下

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
   <!--c3p0配置1-->
    <named-config name="c3p0">
        <!--   连接参数  -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/manager</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <!--  连接池参数  -->
        <property name="idleConnectionTestPeriodInMinutes" value="240"/>
        <property name="idleMaxAgeInMinutes" value="60"/>
        <property name="maxConnectionsPerPartition" value="250"/>
        <property name="minConnectionsPerPartition" value="40"/>
        <property name="partitionCount" value="2"/>
        <property name="acquireIncrement" value="10"/>
        <property name="statementsCacheSize" value="0"/>
        <property name="releaseHelperThreads" value="5"/>
        <property name="connectionTimeoutInMs" value="5000"/>
    </named-config>
</c3p0-config>

1.1.获得c3p0数据连接池的数据源

public class ComboPooledDataSourceUtil {
    //无参构造硬编码(配置这个后无需配置xml)
    public static DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/manager");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        return dataSource;
    }
    //xml编码
    public static DataSource getDataSourceByxml(){
        ComboPooledDataSource cpds=new ComboPooledDataSource("c3p0");
        return cpds;
    }
}

2. dao层采用dbutils工具类操作数据库语句

  @Override
    public Integer delmany(Integer[] ids) throws SQLException {
        String sql = "delete from `grade` where gradeId=?";
        int n=0;
        for (int i = 0; i <ids.length; i++) {
            n = queryRunner.update(sql, ids[i]);
        }

        return n;
    }

3.jsonresult类,向页面输送json格式数据,用于ajax

public class JsonResult {
    private int code;
    private String msg;
    private Object data;

    public JsonResult() {
        super();
    }

    public JsonResult(int code) {
        this.code = code;
    }

    public JsonResult(int code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public JsonResult(int code, Object data) {
        this.code = code;
        this.data = data;
    }

    public JsonResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

 

3.1实体类

public class Grade implements Serializable {


    private Integer gradeid;
    
    private String gradename;
    
    private Integer orderid;

    public Grade(Integer gradeid, String gradename, Integer orderid) {
        this.gradeid = gradeid;
        this.gradename = gradename;
        this.orderid = orderid;
    }
    public Grade() {
    }
    public Integer getGradeid() {
        return gradeid;
    }

    public void setGradeid(Integer gradeid) {
        this.gradeid = gradeid;
    }

    public String getGradename() {
        return gradename;
    }

    public void setGradename(String gradename) {
        this.gradename = gradename;
    }

    public Integer getOrderid() {
        return orderid;
    }

    public void setOrderid(Integer orderid) {
        this.orderid = orderid;
    }
}

4.service层,做业务逻辑

  @Override
    public JsonResult delMnayResult(Integer[] ids) {
        JsonResult jsonResult = null;

        try {
            Integer delmany = gradeDao.delmany(ids);
            if (delmany>0){
                 jsonResult = new JsonResult(200);
            }else {
                jsonResult = new JsonResult(400);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

5.创建servlet抽象类,避免以后一个请求建一个servlet处理类

public abstract class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取模块中方法标识符
        String action = request.getParameter("action");
        if (action == null) {
            action = "index";
        }
        try {
            //1:获取类的字节码
            Class aClass = this.getClass();

            Object o = aClass.newInstance();// 通过类实例化对象

            //方法  方法都是定义在类中,找方法 在类中
            Method method = aClass.getDeclaredMethod(action,
                    HttpServletRequest.class, HttpServletResponse.class);

            Object obj = method.invoke(o, request, response);
            if (obj instanceof String) {
                //转发
                request.getRequestDispatcher(obj.toString()).forward(request, response);
            } else if (obj instanceof JsonResult) {
                //json
                PrintWriter writer = response.getWriter();

                JsonResult jsonResult = (JsonResult) obj;
                String json = JSON.toJSONString(jsonResult);
                writer.print(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

5.1.批量删除servlet类

@WebServlet("/main/grade")
public class GradeServlet extends BaseServlet {
GradeService service = new GradeServiceImpl();
//批量删除
    public JsonResult delMany(HttpServletRequest request, HttpServletResponse response){
        String[]ids=request.getParameterValues("gIDs");
        Integer[]delIds=new Integer[ids.length];
        for (int i = 0; i < ids.length; i++) {
            delIds[i]=Integer.parseInt(ids[i]);
        }
        JsonResult jsonResult = service.delMnayResult(delIds);
        return jsonResult;
    }
}

6. 前端部分代码,此处是列表页面,一般要先做好列表页才能删除,划线代码为预删除勾选按钮

<c:forEach items="${requestScope.grades}" var="grade">
            <tr class="text-c">
                <td><input type="checkbox" value="${grade.gradeid}" id="gIDs" name="gIDs"></td>
                <td id="gid">${grade.gradeid}</td>
                <td><u style="cursor:pointer" class="text-primary">${grade.gradename}</u></td>
                <td>${grade.orderid}</td>
                <td hidden="hidden">13000000000</td>
                <td hidden="hidden">[email protected]</td>
                <td class="text-l" hidden="hidden">北京市 海淀区</td>
                <td hidden="hidden">2014-6-11 11:11:42</td>
                <td class="td-status" hidden="hidden"><span class="label label-success radius">已启用</span></td>
                <td class="td-manage"><a style="text-decoration:none" onClick="member_stop(this,'10001')" href="javascript:;" title="停用"><i class="Hui-iconfont">&#xe631;</i></a> <a title="编辑" href="javascript:;" onclick="member_edit('编辑','/main/grade?action=gradePage&gradeId=${grade.gradeid}','4','','510')" class="ml-5" style="text-decoration:none"><i class="Hui-iconfont">&#xe6df;</i></a> <a style="text-decoration:none" class="ml-5" onClick="change_password('修改密码','change-password.html','10001','600','270')" href="javascript:;" title="修改密码"><i class="Hui-iconfont">&#xe63f;</i></a> <a title="删除" href="javascript:;" onclick="member_del(${grade.gradeid})" class="ml-5" style="text-decoration:none"><i class="Hui-iconfont">&#xe6e2;</i></a></td>
            </tr>
            </c:forEach>
/////代码过多已省略,可在H-UI下载模板
<a href="javascript:;" onclick="datadel()" class="btn btn-danger radius"><i class="Hui-iconfont">&#xe6e2;</i> 批量删除</a>

6.1 重点

 /**批量删除*/
    function datadel() {
        $('input[name="gIDs"]:checked').each(
            function () {
                delgra($(this).val(), this)
            }
        );
    }
    function delgra(id, dome) {
        var url="/main/grade?action=delMany";
        var obj={
            gIDs:id
        }
        $.get(url,obj,function (data) {
            if(data.code=="200"){
                layer.msg("删除成功", {time: 1000, icon: 6, shift: 6});
                location.href="/main/grade";
            }else {
                layer.msg("删除失败", {time: 1000, icon: 5, shift: 6});
            }
        },"json")
    }

7.效果图如下:

'

猜你喜欢

转载自www.cnblogs.com/hyy9527/p/13174337.html