ssm项目之删除员工
本文地址: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哦!
本文版权归作者本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.