7.3 RESTful SpringMVC CRUD(三)

版权声明:转载请注明出处~ 摸摸博主狗头 https://blog.csdn.net/cris_zz/article/details/79968019

用户数据更新

源码点我

1.input.jsp(修改和新增共用一个jsp)

<form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee">
        <!-- path属性对应html标签的name属性 -->
        名字:<form:input path="name"/>
        <br>

        <!-- 要求:不让员工修改邮箱信息 -->
        <!-- 新增用户请求可以添加邮箱信息 -->
        <c:if test="${employee.id == null }">
        邮箱:<form:input path="email"/>
        <br>
        </c:if>

        <!-- 修改用户请求不仅不能修改邮箱信息,还需要将post 请求转换为 put类型 -->
        <c:if test="${employee.id != null }">

            <form:hidden path="id" />
            <input type="hidden" name="_method" value="PUT">        

            <!-- 对于 _method 不能使用 from:hidden 标签,因为 modelAttribute 对应的bean中没有_method 这个属性,如果强行加上会报错 -->

        </c:if>
...

2.后台业务逻辑实现(比较有意思)

    /**
     * 
     * @MethodName: getEmp
     * @Description: TODO (每访问目标带有 pojo 入参的方法时,就会先调用这个带有 @ModelAttribute 注解的方法,来将 pojo类型的
     *                      对象(空白对象或者是从数据库查询的对象)率先放进springMVC的独有的map容器中)
     * @param id
     * @param map
     * @Return Type: void
     * @Author: zc-cris
     */
    @ModelAttribute
    public void getEmp(@RequestParam(value="id", required=false) Integer id, Map<String, Object> map) {
        if(id != null) {
            //说明前台传来的是修改请求
            Employee employee = this.empDao.getEmp(id);
            //将从数据库查询出来的对象放入到map容器中,默认会将空白的Employee 对象放进 Map
            map.put("employee", employee);
        }
    }


    /**
     * 
     * @MethodName: update
     * @Description: TODO (更新用户数据)
     * @return
     * @Return Type: String
     * @Author: zc-cris
     */
    @RequestMapping(value="emp", method=RequestMethod.PUT)
    public String update(Employee employee) {
        //这个目标方法的 pojo 类型参数如果没有 @ModelAttribute 注解修饰指定value,默认会以 pojo 第一个字母小写作为 key 去map容器中查找 该pojo 类型的对象
        this.empDao.save(employee);
        return "redirect:/list";
    }

    /**
     * 
     * @MethodName: input
     * @Description: TODO (先将用户查询出来并显示在页面上)
     * @return
     * @Return Type: String
     * @Author: zc-cris
     */
    @RequestMapping(value="emp/{id}", method=RequestMethod.GET)
    public String input(@PathVariable("id") Integer id, Map<String, Object> map) {
        Employee employee = empDao.getEmp(id);
        map.put("employee", employee);
        map.put("depts", this.deptDao.getDepts());
        return "input";
    }

3.EmpDao

    /**
     * 
     * @MethodName: getEmp
     * @Description: TODO (根据id查询员工对象用于更新)
     * @return
     * @Return Type: Employee
     * @Author: zc-cris
     */
    public Employee getEmp(Integer id) {
        return (Employee) this.emps.get(Integer.toString(id));
    }

4.java测试图:

mark

mark

猜你喜欢

转载自blog.csdn.net/cris_zz/article/details/79968019