SSM项目------员工管理系统(二)

返回JSON数据

当客户端向服务器发送请求的时候,服务器处理完请求,要将页面的数据交给客户端时,如果客户端是安卓或者苹果的话,那样解析服务器传来的数据可能就比较麻烦。所以这里采用一个较为常用的解决方案,那就是让服务器将有效的数据以JSON的形式返回给客户端,这样就可以实现客户端的无关性。

执行流程

  1. 登录成功之后,直接进入list界面,在list页面直接发送ajax请求,进行员工分页数据的查询
  2. 服务器将查出的数据,以json字符串的形式返回给浏览器
  3. 浏览器收到json字符串之后,可以使用js对json进行解析,使用js通过dom增删改改变页面。

web目录

在这里插入图片描述

前端

list.js

var totalRecord;
var httpPath;
var pageNum;

$(function () {
    //页面加载完成之后,直接发送ajax请求,要到分页数据
    httpPath = $("contextPathData").attr("contextPathValue");

    to_page(1);

})

//跳转页面
function to_page(pn) {
    $.ajax({
        url: httpPath + "/emps",
        data: "pn=" + pn,
        type: "GET",
        success: function (result) {
            //console.log(result)
            build_emps_table(result);
            build_page_info(result);
            build_page_nav(result);
            $("#check_all").prop("checked", false)
            $(".check_item").prop("checked", false);
        }
    });
}

/**
 * 解析并显示员工数据
 * @param result
 */
function build_emps_table(result) {
    //清空table
    $("#emps_table tbody").empty();

    var emps = result.ext.pageInfo.list;
    $.each(emps, function (index, item) {
        var empIdTd = $("<td></td>").append(item.empId);
        var empNameTd = $("<td></td>").append(item.empName);
        var genderTd = $("<td></td>").append(item.gender == "M" ? "男" : "女");
        var emailTd = $("<td></td>").append(item.email);
        var deptNameTd = $("<td></td>").append(item.department.deptName);

        var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
            .append($("<span></span>").addClass("glyphicon glyphicon-pencil").attr("aria-hidden", true))
            .append("&nbsp;编辑");

        //为编辑按钮添加一个自定义属性,表示当前的员工id
        editBtn.attr("edit-id", item.empId);


        var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
            .append($("<span></span>").addClass("glyphicon glyphicon-trash").attr("aria-hidden", true))
            .append("&nbsp;删除");

        //为删除按钮添加一个自定义属性,表示当前的员工id
        deleteBtn.attr("delete-id", item.empId);

        var btnTd = $("<td></td>").append(editBtn).append("&nbsp;").append(deleteBtn);
        //append方法执行完成以后还是返回原来的元素
        $("<tr></tr>").append(empIdTd).append(empNameTd).append(genderTd)
            .append(emailTd).append(deptNameTd).append(btnTd).appendTo("#emps_table tbody");
    })
}

/**
 * 解析并显示分页信息
 * @param result
 */
function build_page_info(result) {
    $("#page_info_area").empty();
    $("#page_info_area").append(" 当前为第" + result.ext.pageInfo.pageNum + "页," +
        "共" + result.ext.pageInfo.pages + "页,共" + result.ext.pageInfo.total + "条记录")
    totalRecord = result.ext.pageInfo.total;
    pageNum = result.ext.pageInfo.pageNum;
}

/**
 * 解析并显示分页条
 * @param result
 */
function build_page_nav(result) {
    $("#page_nav_area").empty();

    var ul = $("<ul></ul>").addClass("pagination");

    //如果有前一页
    if (result.ext.pageInfo.hasPreviousPage) {
        //添加首页和前一页的提示
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;").attr("href", "#"));
        ul.append(firstPageLi).append(prePageLi);

        firstPageLi.click(function () {
            to_page(1);
        })
        prePageLi.click(function () {
            to_page(result.ext.pageInfo.pageNum - 1);
        })
    }

    //如果有下一页
    if (result.ext.pageInfo.hasNextPage) {
        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;").attr("href", "#"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
        //添加首页和前一页的提示
        ul.append(nextPageLi).append(lastPageLi);

        nextPageLi.click(function () {
            to_page(result.ext.pageInfo.pageNum + 1);
        })

        lastPageLi.click(function () {
            to_page(result.ext.pageInfo.pages);
        })
    }

    //遍历添加页码
    $.each(result.ext.pageInfo.navigatepageNums, function (index, item) {
        var numLi = $("<li></li>").append($("<a></a>").append(item).attr("href", "#"));
        //设置当前页码的选中状态
        if (result.ext.pageInfo.pageNum == item) {
            numLi.addClass("active");
        }

        numLi.click(function () {
            to_page(item);
        })

        ul.append(numLi);
    })

    ul.append(nextPageLi).append(lastPageLi);

    var navEle = $("<nav></nav>").append(ul);
    navEle.appendTo("#page_nav_area")
}

list.jsp

重写list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: New
  Date: 2020/6/1
  Time: 23:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>员工展示</title>
    <%@include file="common/head.jsp" %>
    <script type="text/javascript" src="${HTTP_PATH}/static/script/list.js"></script>
</head>

<contextPathData contextPathValue="${HTTP_PATH}"></contextPathData>

<body>
<div class="container">

    <%--清除浮动--%>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>员工列表</h1>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4 column">
                <form action="" method="" class="form-inline">
                    <input type="text" placeholder="请输入要查询的员工名称" class="form-control" name="empName">
                    <button class="btn btn-primary">
                        <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                        查询
                    </button>
                </form>
            </div>


            <div class="col-md-4 column">
            </div>

            <div class="col-md-4 column" align="right">
                <button class="btn btn-primary" id="emp_add_modal_btn">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                    新增
                </button>
                <button class="btn btn-danger" id="emp_delete_all_btn">
                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                    删除
                </button>
            </div>
        </div>

    </div>

    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped" id="emps_table">
                <thead>
                <tr>
                    <th>#</th>
                    <th>员工名称</th>
                    <th>性别</th>
                    <th>邮箱</th>
                    <th>部门</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody>
                <tr>

                </tr>

                </tbody>
            </table>
        </div>
    </div>

    <%--显示分页信息--%>
    <div class="row">
        <%--显示文字信息--%>
        <div class="col-md-6" id="page_info_area">
        </div>

        <%--分页条信息--%>
        <div class="col-md-6" id="page_nav_area">

        </div>
    </div>
</div>
</body>
</html>

后端

pom.xml

		<!--jackson插件返回json字符串的支持-->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.8</version>
		</dependency>

Msg.java

统一处理返回的信息以及数据

package com.indi.pojo;

/**
 * 通用返回信息的类
 */
@Getter
@Setter
public class Msg {
    //状态码 100-成功 200-失败
    private int code;
    //提示信息
    private String msg;
    //用户要返回给浏览器的数据
    private Map<String,Object> ext = new HashMap<String, Object>();

    public static Msg success(){
        Msg result = new Msg();
        result.setCode(100);
        result.setMsg("处理成功!");
        return result;
    }

    public static Msg fail(){
        Msg result = new Msg();
        result.setCode(200);
        result.setMsg("处理失败!");
        return result;
    }

    public Msg add(String key, Object value){
        this.getExt().put(key,value);
        return this;
    }
}

UserController.java

直接返回到list界面,由list界面发送数据请求

package com.indi.controller;

@Controller
public class UserController {
    @RequestMapping("/goLogin")
    public String goLogin(HttpSession session, String username, String password, Model model) {
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (user == null) {
            model.addAttribute("msg","用户名或密码错误");
            return "login";
        } else {
            session.setAttribute("user", user);
            return "list";
        }
    }
}

EmployeeController.java

package com.indi.controller;

@Controller
public class EmployeeController {
	//这里将以前的方法废弃

    /**
     * 使用ResponseBody需要导入jackson的jar包
     * 使用ResponseBody自动将对象转为JSON字符串,以实现多种客户端的通用
     *
     * @param pn
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        //调用分页插件的分页方法,传入页码,以及每页显示的条数
        PageHelper.startPage(pn, 5);
        List<Employee> emps = employeeService.getAll();
        PageInfo page = new PageInfo(emps, 5);
        return Msg.success().add("pageInfo", page);
    }
}

员工新增

前端

list.jsp

<body>
	<!-- 员工添加的模态框 -->
	<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	    <div class="modal-dialog" role="document">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
	                </button>
	                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
	            </div>
	            <div class="modal-body">
	                <form class="form-horizontal">
	                    <div class="form-group">
	                        <label for="empName_add_input" class="col-sm-2 control-label">用户名</label>
	                        <div class="col-sm-10">
	                            <input type="text" name="empName" class="form-control" id="empName_add_input"
	                                   placeholder="用户名">
	                            <span class="help-block"></span>
	                        </div>
	                    </div>
	                    <div class="form-group">
	                        <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
	                        <div class="col-sm-10">
	                            <input type="email" name="email" class="form-control" id="email_add_input"
	                                   placeholder="email@qq.com">
	                            <span class="help-block"></span>
	                        </div>
	                    </div>
	                    <div class="form-group">
	                        <label for="email_add_input" class="col-sm-2 control-label">性别</label>
	                        <div class="col-sm-10">
	                            <label class="radio-inline">
	                                <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"></label>
	                            <label class="radio-inline">
	                                <input type="radio" name="gender" id="gender2_add_input" value="F"></label>
	                        </div>
	                    </div>
	
	                    <div class="form-group">
	                        <label for="email_add_input" class="col-sm-2 control-label">部门</label>
	                        <div class="col-sm-4">
	                            <select class="form-control" name="dId" id="dept_add_select"></select>
	                        </div>
	                    </div>
	                </form>
	            </div>
	            <div class="modal-footer">
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
	            </div>
	        </div>
	    </div>
	</div>
	
	<!--...之前的代码...-->
</body>

list.js

在原来基础上添加新的代码

$(function () {

	//之前的代码
	
    //点击新增按钮的事件
    $("#emp_add_modal_btn").click(function () {
        getDepts("#empAddModal select");

        reset_form("#empAddModal form");

        //显示模态框
        $("#empAddModal").modal({
            backdrop: "static"
        });
    })

	//模态框保存按钮
    $("#emp_save_btn").click(function () {
        //1、校验用户名
        var empName = $("#empName_add_input");
        var regName = /^[a-zA-Z0-9_-]{6,16}|(^[\u2E80-\u9FFF]{2,5})$/;

        if (!regName.test(empName.val())) {
            //alert("用户名可以是2-5位中文,或者6-13位英文和数字的组合");
            show_validata_msg(empName, "error", "用户名必须是2-5位中文,或者6-13位英文和数字的组合");
            return false;
        } else {
            show_validata_msg(empName, "success", "用户名可用");
        }

        //2、校验邮箱
        var email = $("#email_add_input");

        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

        if (!regEmail.test(email.val())) {
            show_validata_msg(email, "error", "邮箱格式不正确");
            return false;
        } else {
            //3、请求保存数据
            $.ajax({
                url: httpPath + "/emp",
                type: "POST",
                data: $("#empAddModal form").serialize(),
                success: function (result) {
                    //alert(result.msg);
                    if (result.code == 100) {
                        //成功
                        //1、关闭模态框
                        $("#empAddModal").modal('hide');
                        //2、发送ajax请求,来到最后一页,显示刚才保存的数据
                        to_page(totalRecord + 1);
                    } else {
                        // console.log(result);
                        if (undefined != result.ext.errorMap.email) {
                            show_validata_msg(email, "error", result.ext.errorMap.email);
                        } else {
                            show_validata_msg(email, "success", "邮箱可用");
                        }

                        if (undefined != result.ext.errorMap.empName) {
                            show_validata_msg(empName, "error", result.ext.errorMap.empName);
                        } else {
                            show_validata_msg(empName, "success", "用户名可用");
                        }
                    }

                }
            })
        }
    })

    //新增模态框的用户名校验
    $("#empName_add_input").blur(function () {
        setTimeout(function () {
            var empName = $("#empName_add_input");
            var regName = /^[a-zA-Z0-9_-]{6,16}|(^[\u2E80-\u9FFF]{2,5})$/
            if (!regName.test(empName.val())) {
                show_validata_msg(empName, "error", "用户名必须是2-5位中文,或者6-13位英文和数字的组合");
            } else {
                show_validata_msg(empName, "success", "用户名可用");
            }
        },300);
    })

    //邮箱校验
    $("#email_add_input").blur(function () {
        setTimeout(function () {
            var email = $("#email_add_input");

            var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            if (!regEmail.test(email.val())) {
                //alert("邮箱格式不正确")
                show_validata_msg(email, "error", "邮箱格式不正确");
            } else {
                $.ajax({
                    url: httpPath + "/checkEmail",
                    data: "email=" + email.val(),
                    type: "POST",
                    success: function (result) {
                        if (result.code == 100) {
                            show_validata_msg(email, "success", "邮箱可用");
                        } else {
                            show_validata_msg(email, "error", result.ext.va_msg);
                        }
                    }
                })
            }
        },300)
    })
})

//之前的代码

/**
 * 查出所有部门信息系并显示在下拉列表中
 */
function getDepts(ele) {
    $(ele).empty();
    $.ajax({
        url: httpPath + "/depts",
        type: "GET",
        success: function (result) {
            // console.log(result);
            $.each(result.ext.depts, function () {
                var optionEle = $("<option></option>").append(this.deptName).attr("value", this.deptId);
                optionEle.appendTo(ele);
            })
        }
    })
}

//设置输入框的校验提示
function show_validata_msg(ele, status, msg) {
    ele.parent().removeClass("has-success has-error");
    ele.next("span").text("");
    if ("success" == status) {
        ele.parent().addClass("has-success");
        ele.next("span").text(msg);
    } else if ("error" == status) {
        ele.parent().addClass("has-error");
        ele.next("span").text(msg);
    }
}

/**
 * 清除模态框样式及内容
 * @param ele
 */
function reset_form(ele) {
    $(ele)[0].reset();
    $(ele).find("*").removeClass("has-error has-success");
    $(ele).find(".help-block").text("");
}

后端

pom.xml

在后端添加JSR303数据校验

		<!--JSR303数据校验支持-->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.4.1.Final</version>
		</dependency>

DepartmentService.java

package com.indi.service;

@Service
public class DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    public List<Department> getDepts(){
        List<Department> departments = departmentMapper.selectByExample(null);
        return departments;
    }
}

DepartmentController.java

package com.indi.controller;

import java.util.List;

/**
 * 处理和部门有关的请求
 */
@Controller
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 查询所有的部门信息
     * @return
     */
    @RequestMapping("/depts")
    @ResponseBody
    public Msg getDepts(){
        List<Department> depts = departmentService.getDepts();
        return Msg.success().add("depts",depts);
    }
}

Employee.java

为这两个字段添加后端校验

package com.indi.pojo;

@Data
@NoArgsConstructor
public class Employee {

    @Pattern(regexp = "^[a-zA-Z0-9_-]{6,16}|(^[\\u2E80-\\u9FFF]{2,5})$",message = "用户名必须是2-5位中文,或者6-13位英文和数字的组合")
    private String empName;

    @Pattern(regexp = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",message = "邮箱格式不正确")
    private String email;
}

EmployeeService.java

package com.indi.service;

@Service
public class EmployeeService {

	//之前的代码
	
    public void saveEmp(Employee employee) {
        employeeMapper.insertSelective(employee);
    }

    /**
     * 检查邮箱是否重复
     * @param email
     * @return true代表当前email可用,false代表不可用
     */
    public boolean checkEmail(String email) {
        EmployeeExample example = new EmployeeExample();
        Criteria criteria = example.createCriteria();
        criteria.andEmailEqualTo(email);
        long count = employeeMapper.countByExample(example);
        return count == 0;
    }
}

EmployeeController.java

package com.indi.controller;

@Controller
public class EmployeeController {
	//之前的代码

    /**
     *  新增员工
     *
     * @return
     */
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result) {
        Map<String, Object> errorMap = new HashMap<>();

        //校验数据格式是否正确
        if (result.hasErrors()) {
            //校验失败,应该返回失败,在模态框中显示校验失败的错误信息
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError error : errors) {
                System.out.println("错误的字段名:" + error.getField());
                System.out.println("错误信息:" + error.getDefaultMessage());
                errorMap.put(error.getField(), error.getDefaultMessage());
            }
            //如果错误集合中不包含邮箱,则证明邮箱格式没问题,此时需要检查邮箱是否重复,
            //否则会与数据格式都正确的提示发生冲突,导致显示异常
            if (!errors.contains("email")) {
                //检查邮箱是否重复
                boolean res = employeeService.checkEmail(employee.getEmail());
                if (!res) {
                    errorMap.put("email", "该邮箱已使用");
                }
            }
            return Msg.fail().add("errorMap", errorMap);
        } else {
            //如果数据格式都正确,则需要检查邮箱是否重复
            boolean res = employeeService.checkEmail(employee.getEmail());
            if (res) {
                employeeService.saveEmp(employee);
                return Msg.success();
            } else {
                errorMap.put("email", "该邮箱已使用");
                return Msg.fail().add("errorMap", errorMap);
            }
        }
    }

    /**
     * 检查邮箱是否可用
     *
     * @param email
     * @return
     */
    @RequestMapping("/checkEmail")
    @ResponseBody
    public Msg checkEmail(@RequestParam("email") String email) {
        //先判断邮箱是否合法
        String regx = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$";
        if (!email.matches(regx)) {
            return Msg.fail().add("va_msg", "邮箱格式不正确");
        }

        //数据库邮箱重复校验
        boolean res = employeeService.checkEmail(email);
        if (res) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "该邮箱已使用");
        }
    }	
}

员工修改

前端

list.js

$(function () {
	//更新模态框的用户名校验
    $("#empName_update_input").blur(function () {
        //设置延时解决click与blur冲突的问题
        setTimeout(function () {
            var empName = $("#empName_update_input");
            var regName = /^[a-zA-Z0-9_-]{6,16}|(^[\u2E80-\u9FFF]{2,5})$/
            if (!regName.test(empName.val())) {
                show_validata_msg(empName, "error", "用户名必须是2-5位中文,或者6-13位英文和数字的组合");
            } else {
                show_validata_msg(empName, "success", "用户名可用");
            }
        }, 300)
    })

    //更新按钮的点击事件
    $("#emp_update_btn").click(function () {
        //1、校验用户名
        var empName = $("#empName_update_input");
        var regName = /^[a-zA-Z0-9_-]{6,16}|(^[\u2E80-\u9FFF]{2,5})$/;

        if (!regName.test(empName.val())) {
            //alert("用户名可以是2-5位中文,或者6-13位英文和数字的组合");
            show_validata_msg(empName, "error", "用户名必须是2-5位中文,或者6-13位英文和数字的组合");
            return false;
        } else {
            show_validata_msg(empName, "success", "用户名可用");
            $.ajax({
                url: httpPath + "/updateEmp/" + $(this).attr("edit-id"),
                type: "PUT",
                data: $("#empUpdateModal form").serialize(),
                success: function (result) {
                    // console.log(result);
                    if (result.code == 100) {
                        //成功
                        //1、关闭模态框
                        show_validata_msg(empName, "success", "用户名可用");
                        $("#empUpdateModal").modal('hide');
                        to_page(pageNum);
                    } else {
                        show_validata_msg(empName, "error", result.ext.va_msg);
                        return false;
                    }
                }
            })
        }
    })

	//为列表项中的修改添加点击事件
    $(document).on("click", ".edit_btn", function () {
        reset_form("#empUpdateModal form");
        // alert("edit");
        //1、查出部门信息,显示部门列表
        getDepts("#empUpdateModal select");

        //2、查出员工信息,显示员工信息
        getEmp($(this).attr("edit-id"));

        //3、把员工id传给模态框的更新按钮
        $("#emp_update_btn").attr("edit-id", $(this).attr("edit-id"));

        $("#empUpdateModal").modal({
            backdrop: "static"
        });
    })
})

/**
 * 根据id查询出用户信息并赋值
 * @param id
 */
function getEmp(id) {
    $.ajax({
        url: httpPath + "/emp/" + id,
        type: "GET",
        success: function (result) {
            //console.log(result);
            var empData = result.ext.emp;
            $("#empName_update_input").val(empData.empName);
            $("#email_update_static").text(empData.email);
            $("#empUpdateModal input[name=gender]").val([empData.gender]);
            $("#empUpdateModal select").val([empData.dId]);
        }
    })
}

list.jsp

<body>
	<!-- 员工修改的模态框 -->
	<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	    <div class="modal-dialog" role="document">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
	                </button>
	                <h4 class="modal-title">员工修改</h4>
	            </div>
	            <div class="modal-body">
	                <form class="form-horizontal">
	                    <div class="form-group">
	                        <label for="empName_add_input" class="col-sm-2 control-label">用户名</label>
	                        <div class="col-sm-10">
	                            <input type="text" name="empName" class="form-control" id="empName_update_input"
	                                   placeholder="用户名">
	                            <span class="help-block"></span>
	                        </div>
	                    </div>
	                    <div class="form-group">
	                        <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
	                        <div class="col-sm-10">
	                            <p class="form-control-select" id="email_update_static"></p>
	                        </div>
	                    </div>
	                    <div class="form-group">
	                        <label for="email_add_input" class="col-sm-2 control-label">性别</label>
	                        <div class="col-sm-10">
	                            <label class="radio-inline">
	                                <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"></label>
	                            <label class="radio-inline">
	                                <input type="radio" name="gender" id="gender2_update_input" value="F"></label>
	                        </div>
	                    </div>
	
	                    <div class="form-group">
	                        <label for="email_add_input" class="col-sm-2 control-label">部门</label>
	                        <div class="col-sm-4">
	                            <select class="form-control" name="dId" id="dept_update_select"></select>
	                        </div>
	                    </div>
	                </form>
	            </div>
	            <div class="modal-footer">
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
	            </div>
	        </div>
	    </div>
	</div>
</body>

后端

web.xml

	<!-- 添加FormContentFilter过滤器以支持PUT请求--->
	<filter>
		<filter-name>FormContentFilter</filter-name>
		<filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>FormContentFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

EmployeeService.java

package com.indi.service;

@Service
public class EmployeeService {

	//之前的代码
	
    /**
     * 根据员工id查询员工信息
     * @param id
     * @return
     */
    public Employee getEmp(Integer id){
        Employee employee = employeeMapper.selectByPrimaryKeyWithDept(id);
        return employee;
    }

    /**
     * 员工更新
     * @param employee
     */
    public void updateEmp(Employee employee) {
        employeeMapper.updateByPrimaryKeySelective(employee);
    }
}

EmployeeController.java

package com.indi.controller;

@Controller
public class EmployeeController {
	//之前的代码

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id") Integer id) {
        Employee emp = employeeService.getEmp(id);
        return Msg.success().add("emp", emp);
    }

    /**
     * 更新员工
     *
     * @param employee
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateEmp/{empId}", method = RequestMethod.PUT)
    public Msg updateEmp(Employee employee) {
        String regx = "^[a-zA-Z0-9_-]{6,16}|(^[\\u2E80-\\u9FFF]{2,5})$";
        if (!employee.getEmpName().matches(regx)) {
            return Msg.fail().add("va_msg", "用户名必须是2-5位中文,或者6-13位英文和数字的组合");
        } else {
            employeeService.updateEmp(employee);
            return Msg.success();
        }
    }
}

员工删除

前端

list.js

$(function () {
    //为列表项中的删除添加点击事件
    $(document).on("click", ".delete_btn", function () {
        //1、弹出是否确认删除对话框
        var empName = $(this).parents("tr").find("td:eq(2)").text();
        var empId = $(this).attr("delete-id");
        if (confirm("确认删除【" + empName + "】吗?")) {
            //确认
            $.ajax({
                url: httpPath + "/deleteEmp/" + empId,
                type: "DELETE",
                success: function (result) {
                    //alert(result.msg)
                    to_page(pageNum);
                }
            })
        }
    })
})

后端

EmployeeService.java

package com.indi.service;

@Service
public class EmployeeService {

	//之前的代码
	
    /**
     * 员工删除
     * @param id
     */
    public void deleteEmp(Integer id) {
        employeeMapper.deleteByPrimaryKey(id);
    }
}

EmployeeController.java

package com.indi.controller;

@Controller
public class EmployeeController {
	//之前的代码

    @ResponseBody
    @RequestMapping(value = "/deleteEmp/{id}", method = RequestMethod.DELETE)
    public Msg deleteEmpById(@PathVariable("id")Integer id) {
        employeeService.deleteEmp(id);
        return Msg.success();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值