本文地址:http://www.cnblogs.com/maplefighting/p/7544483.html
刪除可以分為單個刪除和批量刪除
一、單個刪除
employeeController.java

/** * 刪除員工 * @param id * @return
*/ @ResponseBody @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE) public Msg deleteEmpById(@PathVariable("id")Integer id) { //Integer id = Integer.parseInt(id);
employeeService.deleteEmp(id); return Msg.success(); }
employeeService.java

/** * 員工刪除 * @param id */
public void deleteEmp(Integer id) { employeeMapper.deleteByPrimaryKey(id); }
index.jsp

//單個刪除
$(document).on("click",".delete_btn", function(){
//1、彈出確認刪除對話框
var empName = $(this).parents("tr").find("td:eq(2)").text();
var empId = $(this).attr("del-id");
if(confirm("確認刪除【" + empName + "】嗎?")) {
//確認,發送 Ajax
$.ajax({
url: "${APP_PATH}/emp/" + empId,
type: "DELETE",
success: function(result) {
alert(result.msg);
//回到本頁
to_page(currentPage);
}
});
}
});
二、批量刪除
先完成前面那個點擊最上面全選全不選的功能

//完成全選全不選
$("#check_all").click(function() { //prop修改和讀取原生dom屬性的值
$(".check_item").prop("checked", $(this).prop("checked")); }); $(document).on("click",".check_item", function() { var flag = $(".check_item:checked").length == $(".check_item").length; $("#check_all").prop("checked", flag); });
點擊批量刪除

//點擊全部刪除,就批量刪除
$("#emp_delete_all_btn").click(function() { var empNames = ""; var del_idstr = ""; $.each($(".check_item:checked"), function() { empNames += $(this).parents("tr").find("td:eq(2)").text() + ","; del_idstr += $(this).parents("tr").find("td:eq(1)").text() + "-"; }); empNames = empNames.substring(0, empNames.length - 1); del_idstr = del_idstr.substring(0, del_idstr.length - 1); if(confirm("確認刪除【" + empNames + "】嗎?")) { $.ajax({ url:"${APP_PATH}/emp/" + del_idstr, type:"DELETE", success:function(result) { alert(result.msg); to_page(currentPage); } }); } });
批量刪除的直接用橫杠拼接起來,單個刪除和批量刪除放在一起處理
EmployeeController.java

/** * 單個或批量刪除員工 * @param id * @return
*/ @ResponseBody @RequestMapping(value="/emp/{ids}", method=RequestMethod.DELETE) public Msg deleteEmpById(@PathVariable("ids")String ids) { //批量刪除
if(ids.contains("-")) { List<Integer> del_ids = new ArrayList<>(); String[] str_ids = ids.split("-"); for(String string : str_ids) { del_ids.add(Integer.parseInt(string)); } employeeService.deleteBatch(del_ids); } else { //單個刪除
Integer id = Integer.parseInt(ids); employeeService.deleteEmp(id); } return Msg.success(); }
EmployeeService.java

/** * 員工單個刪除 * @param id */
public void deleteEmp(Integer id) { employeeMapper.deleteByPrimaryKey(id); } /** * 批量刪除 * @param ids */
public void deleteBatch(List<Integer> ids) { EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); //delete from xxxx where emp_id in (1,2,3)
criteria.andEmpIdIn(ids); employeeMapper.deleteByExample(example); }
測試
單個
批量
這樣CRUD就做完了,不過Controller里的一些邏輯啥的最好放在Service層,畢竟Service層才是主要寫邏輯的,反正怎么順手怎么來吧
項目完整代碼github地址:https://github.com/maplewtf/ssm-crud 覺得寫得還可以的不要忘記點個star哦!