1. 程式人生 > >SpringMVC_14_RESTFUL_CRUD(五)實現修改操作PUT

SpringMVC_14_RESTFUL_CRUD(五)實現修改操作PUT

完成了DELETE刪除操作,最後我們一鼓作氣 完成修改操作吧!

修改操作,點選修改功能的< a>標籤後,在handler方法中根據id找到當前Employee的所有資料,放在request域中,轉到input.jsp頁面中,這樣input.jsp就能直接顯示原來的資料,而不是之前的註冊介面啥內容都沒有填寫。修改完畢這時提交方法是PUT,需要寫一個新的handler方法處理PUT操作,最後重定向到list.jsp即可。那這裡需要注意的是,修改的時候不能修改lastName這個屬性,所有修改介面不能顯示這個text。

一、先寫好list.jsp頁面中的修改功能的< a>標籤 的href和處理方法

<td><a href="emp/${emp.id}">Edit</a></td>  //這裡需要當前的id,方便根據id查詢

這一步跳轉到input.jsp並且是當前Employee的資料,但是不會顯示lastName.

//以下這個方法的目的是當你想要修改的時候,顯示出原始資料
@RequestMapping(value="/emp/{id}",method = RequestMethod.GET)
public String input(@PathVariable("id") Integer id ,Map<String,Object>
map){ map.put("employee",employeeDao.get(id)); map.put("departments",departmentDao.getDepartments()); return "input"; }

二、input.jsp判斷為修改還是新增操作

<c:if test="${employee.id==null}">
<!--Path 屬性對應html表單標籤的name屬性值-->
LastName: <form:input path="lastName"/>
</c:if>
<
c:if
test="${employee.id!=null}">
<form:hidden path="id"/> <%--對於_method 不能使用form:hidden標籤,因為modelAtttibute 對應的bean中沒有_method這個屬性--%> <input type="hidden" name="_method" value="PUT"/> </c:if>

現在的input.jsp

<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <!--
        1.WHY使用form標籤呢?
        可以更快速的開發出表單頁面,而且可以更方便的進行表單值的回顯
        2.注意:
        可以通過modelAttribute屬性指定繫結的模型屬性,
        則預設為request域物件中讀取command的表單的bean.
        如果該屬性值也不存在,則會發生錯誤。
    -->
    <form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee">

        <c:if test="${employee.id==null}">
        <!--Path 屬性對應html表單標籤的name屬性值-->
        LastName: <form:input path="lastName"/>
        </c:if>
        <c:if test="${employee.id!=null}">
            <form:hidden path="id"/>
            <%--對於_method 不能使用form:hidden標籤,因為modelAtttibute 對應的bean中沒有_method這個屬性--%>
            <input type="hidden" name="_method" value="PUT"/>
        </c:if>
        <br>
        Email:<form:input path="email"/>
        <br>
        <%
            Map<String,String> genders = new HashMap<String, String>();
            genders.put("1","Male");
            genders.put("0","Female");

            request.setAttribute("genders",genders);
        %>
        Gender:
        <br>
        <form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/>
        <br>
        Department:<form:select path="department.id"
                                items="${departments}" itemLabel="departmentName" itemValue="id"></form:select>
        <br>
        <input type="submit" value="Submit"/>
    </form:form>

</body>
</html>

三、編寫PUT請求的handler方法

@RequestMapping(value = "/emp",method = RequestMethod.PUT)
public String update(Employee employee){
    employeeDao.save(employee);

    return "redirect:/emps";
}

四、@ModelAttribute

如果直接使用這個修改功能,會發現修改後的list.jsp裡,修改的那個Employee的id消失了,這是因為修改的時候,是new了一個Employee填入修改後的資料後(修改的時候沒有id這個值),放入資料庫就覆蓋了原來的資料,造成id資料的丟失。

處理方法:使用@ModelAttribute使得修改前首先根據id拿出所有的資料放在Employee中,而不是新new一個,這樣修改過後,放回資料庫時,本身就攜帶了id這個資料。

//這個的目的在於完成修改的操作時候,不會丟失id的資料
@ModelAttribute
public void getEmployee(@RequestParam(value="id",required = false) Integer id,
                        Map<String,Object> map){

    if(id!=null){
        map.put("employee",employeeDao.get(id));
    }

}

當前的EmployeeHandler.java

package com.springmvc.crud.handlers;

import com.springmvc.crud.dao.DepartmentDao;
import com.springmvc.crud.dao.EmployeeDao;
import com.springmvc.crud.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;


    //這個的目的在於完成修改的操作時候,不會丟失id的資料
    @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required = false) Integer id,
                            Map<String,Object> map){

        if(id!=null){
            map.put("employee",employeeDao.get(id));
        }

    }

    @RequestMapping(value = "/emp",method = RequestMethod.PUT)
    public String update(Employee employee){
        employeeDao.save(employee);

        return "redirect:/emps";
    }

    //以下這個方法的目的是當你想要修改的時候,顯示出原始資料
    @RequestMapping(value="/emp/{id}",method = RequestMethod.GET)
    public String input(@PathVariable("id") Integer id ,Map<String,Object> map){
        map.put("employee",employeeDao.get(id));
        map.put("departments",departmentDao.getDepartments());
        return "input";
    }

    @RequestMapping(value="/emp/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    public String save(Employee employee){

        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping(value="emp",method = RequestMethod.GET)
        public String input(Map<String,Object> map){
        map.put("departments",departmentDao.getDepartments());
        map.put("employee",new Employee());
        return "input";
    }


    @RequestMapping("/emps")
    public String list(Map<String,Object> map){

        map.put("employees",employeeDao.getAll());
        return "list";
    }

}

當前的input.jsp

<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: 14741
  Date: 2019/1/2
  Time: 20:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <!--
        1.WHY使用form標籤呢?
        可以更快速的開發出表單頁面,而且可以更方便的進行表單值的回顯
        2.注意:
        可以通過modelAttribute屬性指定繫結的模型屬性,
        則預設為request域物件中讀取command的表單的bean.
        如果該屬性值也不存在,則會發生錯誤。
    -->
    <form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee">

        <c:if test="${employee.id==null}">
        <!--Path 屬性對應html表單標籤的name屬性值-->
        LastName: <form:input path="lastName"/>
        </c:if>
        <c:if test="${employee.id!=null}">
            <form:hidden path="id"/>
            <%--對於_method 不能使用form:hidden標籤,因為modelAtttibute 對應的bean中沒有_method這個屬性--%>
            <input type="hidden" name="_method" value="PUT"/>
        </c:if>
        <br>
        Email:<form:input path="email"/>
        <br>
        <%
            Map<String,String> genders = new HashMap<String, String>();
            genders.put("1","Male");
            genders.put("0","Female");

            request.setAttribute("genders",genders);
        %>
        Gender:
        <br>
        <form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/>
        <br>
        Department:<form:select path="department.id"
                                items="${departments}" itemLabel="departmentName" itemValue="id"></form:select>
        <br>
        <input type="submit" value="Submit"/>
    </form:form>

</body>
</html>