基于ssm框架下进行的批量删除

引言:开发web项目时,批量删除作为一个重要的操作模块必不可少,对于很多Java初学者是一个很大的麻烦,我


看了很多关于批量删除写的博客,漏洞百出,因此在我解决问题之后写下一篇博客对那些需要帮助的人指一条明路。

思路:基于ssm框架,利用js和ajax勾选复选框发出请求到Controller进行批量删除操作。


1、数据库表的设计

CREATE TABLE `qualification` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `classification` varchar(45) DEFAULT NULL,
  `name` varchar(45) DEFAULT NULL,
  `description` varchar(150) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8;
SELECT * FROM shop.qualification;


插入几条数据


2、编写Qualification的实体类。

package com.lysoc.jmi.tracing.model;

import java.io.Serializable;

public class Qualification  implements Serializable {//实现序列化是为了方便传输数据
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getClassification() {
        return classification;
    }
    public void setClassification(String classification) {
        this.classification = classification;
    }
    private Integer id;
    private String name;
    private String description;
    private String classification;

}


3、Mapper层(相当于dao层,操作数据库的)

    public int deleteMany(String [] ids);


4、配置sql语句

<delete id="deleteMany" parameterType="java.lang.String" >
          delete  from  qualification where id in
           <foreach item="ids" collection="array" index="no" open="(" separator="," close=")">
              #{ids}
          </foreach> 

  </delete> 

注意要添加QualificationMapper.xml到mybatis.config.xml的配置文件

<mapper resource="com/lysoc/jmi/tracing/mapper/QualificationMapper.xml"/>


5、通过js和ajax发出请求到Controller

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<% pageContext.setAttribute("path",request.getContextPath()); %>加这条语句,避免访问出错。
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>资质信息</title>
<script  type="text/javascript" src="./js/jquery-1.8.2.js"></script>
<script>
function todelect(){
    var Checkbox=false;//默认复选框为空
     $("input[name='id']").each(function(){//获取复选框节点id
      if (this.checked==true) {        
        Checkbox=true;    //已勾选
      }
    });
    if (Checkbox){//boolean值为true
        var t=confirm("您确认要删除选中的内容吗?");//弹出对话进行警告
        if (t==false) return false;    //不勾选不处理
        obj = document.getElementsByName("id");//将复选框定义成一个jquery对象
        check_val = [];//定义一个数组
        for(k in obj){//k相当于i,往这个jquery对象添加勾选的id;
            if(obj[k].checked)//选中的都放进 数组里
                check_val.push(obj[k].value);
        }
   
        $.ajax({//利用ajax发出请求
            type:"POST",//post类型
            url:"${path}/deleteMany?ids="+check_val, //向Controller里的deleteSelect传输ids
            success:function(data){//删除成功后,deleteMany会返回一个"ok";
            if(data=="ok"){
                alert("删除成功!");//返回ok后弹出一个对话框。
                location.href="${path}/Mainpage";//相当于刷新界面
            }
        } 
});
      
    }
    else{
        alert("请选择您要删除的内容!");//不勾选不提交,弹出警告框。
        return false;
    }
    
    
}


6、Service层(编写实现类)

我在业务逻辑层就不写接口和Impl类了,直接写实现类

@Service
public class QuaService {
    
    @Autowired
    QualificationMapper qmap;
   public Integer deleteMany(String[] ids) {
        return qmap.deleteMany(ids);
    } 

}
 


7、Controller层


@Controller
public class QualificationController {
        @Autowired
        private QuaService quaService;
        @RequestMapping(value="/deleteSelect")
        @ResponseBody
        public String deleteSelect(String ids,Model model){
            System.err.println(ids);
            String[] d=ids.split(",");//把数组里的值逗号隔开
            System.out.println("批量删除成功");
            quaService.deleteMany(d);
            return "ok";//返回给ajax
        }
    }


8、View层(qualification_main.jsp)

<table id="form">
    <tr><th><input type="checkbox" name="selectall" id="selectall"/></th><th>序号</th><th>类别</th><th>名称</th><th>描述</th></tr>
    <c:forEach items="${pagemsg.lists}" var="qua">
    <tr>
        <td><input type="checkbox" name="id" value="${qua.id }"/></td>
        <td>${qua.id}</td>
        <td>${qua.classification}</td>
        <td>${qua.name}  </td>
        <td>${qua.description}</td>
        
        
    </tr>

    批量删除的前提是做好分页查询。
    </c:forEach>
    
</table>

<table >
    <tr>
    <td class="td2">
   <span>第${requestScope.pagemsg.currPage}/ ${requestScope.pagemsg.totalPage}页</span> 
   <span>总记录数:${requestScope.pagemsg.totalCount } 每页显示:
                   ${requestScope.pagemsg.pageSize}</span> 
   <span>
       <c:if test="${requestScope.pagemsg.currPage != 1}">
           <a href="${pageContext.request.contextPath }/Mainpage?currentPage=1">[首页]</a> 
           <a href="${pageContext.request.contextPath }/Mainpage?currentPage=${requestScope.pagemsg.currPage-1}">[上一页]</a> 
       </c:if>
       <c:if test="${requestScope.pagemsg.currPage != requestScope.pagemsg.totalPage}">
           <a href="${pageContext.request.contextPath }/Mainpage?currentPage=${requestScope.pagemsg.currPage+1}">[下一页]</a>  
           <a href="${pageContext.request.contextPath }/Mainpage?currentPage=${requestScope.pagemsg.totalPage}">[尾页]</a>  
       </c:if>

   </span>
    </td>
    </tr>
    </table>

 
<button id="btn2" onclick="return  todelect()">批量删除</button>
 


9、效果图给大家演示一下


 


由于时间原因,精力有限,编辑器不好用,代码写的不够整洁还望见谅,以上代码经过验证,成功实现批量删除的功能。

猜你喜欢

转载自blog.csdn.net/liqz666/article/details/81541665