SpringMVC:RESTful案例

愚生淺末發表於2023-02-25

相關準備

和傳統 CRUD 一樣,實現對員工資訊的增刪改查。

  • 搭建環境
  • 準備實體類
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    //1 male, 0 female
    private Integer gender;
    //getter,setter,有參無參
}
  • 準備dao模擬資料
@Repository
public class EmployeeDao {
    private static Map<Integer, Employee> employees = null;
    static{
        employees = new HashMap<Integer, Employee>();
        employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
    }
    private static Integer initId = 1006;
    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }
    public Collection<Employee> getAll(){
        return employees.values();
    }
    public Employee get(Integer id){
        return employees.get(id);
    }
    public void delete(Integer id){
        employees.remove(id);
    }
}

功能清單

功能 URL 地址 請求方式
訪問首頁√ / GET
查詢全部資料√ /employee GET
刪除√ /employee/2 DELETE
跳轉到新增資料頁面√ /toAdd GET
執行儲存√ /employee POST
跳轉到更新資料頁面√ /employee/2 GET
執行更新√ /employee PUT

具體功能:訪問首頁

①配置view-controller

<mvc:view-controller path="/" view-name="index"/>

②建立頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" >
        <title>Title</title>
    </head>
    <body>
        <h1>首頁</h1>
        <a th:href="@{/employee}">訪問員工資訊</a>
    </body>
</html>

具體功能:查詢所有員工資料

①控制器方法

@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getEmployeeList(Model model){
    Collection<Employee> employeeList = employeeDao.getAll();
    model.addAttribute("employeeList", employeeList);
    return "employee_list";
}

②建立employee_list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Employee Info</title>
        <script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
    </head>
    <body>
        <table border="1" cellpadding="0" cellspacing="0" style="text-align:center;" id="dataTable">
            <tr>
                <th colspan="5">Employee Info</th>
            </tr>
            <tr>
                <th>id</th>
                <th>lastName</th>
                <th>email</th>
                <th>gender</th>
                <th>options(<a th:href="@{/toAdd}">add</a>)</th>
            </tr>
            <tr th:each="employee : ${employeeList}">
                <td th:text="${employee.id}"></td>
                <td th:text="${employee.lastName}"></td>
                <td th:text="${employee.email}"></td>
                <td th:text="${employee.gender}"></td>
                <td>
                    <a class="deleteA" @click="deleteEmployee"
                       th:href="@{'/employee/'+${employee.id}}">delete</a>
                    <a th:href="@{'/employee/'+${employee.id}}">update</a>
                </td>
            </tr>
        </table>
    </body>
</html>

具體功能:刪除

①建立處理delete請求方式的表單

<!-- 作用:透過超連結控制表單的提交,將post請求轉換為delete請求 -->
<form id="delete_form" method="post">
    <!-- HiddenHttpMethodFilter要求:必須傳輸_method請求引數,並且值為最終的請求方式 -->
    <input type="hidden" name="_method" value="delete"/>
</form>

引入vue.js

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>

刪除超連結

<a class="deleteA" @click="deleteEmployee"th:href="@{'/employee/'+${employee.id}}">delete</a>

透過vue處理點選事件

<script type="text/javascript">
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            //event表示當前事件
            deleteEmployee:function (event) {
                //透過id獲取表單標籤
                var delete_form = document.getElementById("delete_form");
                //將觸發事件的超連結的href屬性為表單的action屬性賦值
                delete_form.action = event.target.href;
                //提交表單
                delete_form.submit();
                //阻止超連結的預設跳轉行為
                event.preventDefault();
            }
        }
    });
</script>

③控制器方法

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

具體功能:跳轉到新增資料頁面

①配置view-controller

<mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>

②建立employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Add Employee</title>
    </head>
    <body>
        <form th:action="@{/employee}" method="post">
            lastName:<input type="text" name="lastName"><br>
            email:<input type="text" name="email"><br>
            gender:<input type="radio" name="gender" value="1">male
            <input type="radio" name="gender" value="0">female<br>
            <input type="submit" value="add"><br>
        </form>
    </body>
</html>

具體功能:執行儲存

①控制器方法

@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

具體功能:跳轉到更新資料頁面

①修改超連結

<a th:href="@{'/employee/'+${employee.id}}">update</a>

②控制器方法

@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}

③建立employee_update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Update Employee</title>
    </head>
    <body>
        <form th:action="@{/employee}" method="post">
            <input type="hidden" name="_method" value="put">
            <input type="hidden" name="id" th:value="${employee.id}">
            lastName:<input type="text" name="lastName" th:value="${employee.lastName}">
            <br>
            email:<input type="text" name="email" th:value="${employee.email}"><br>
            <!--
                th:field="${employee.gender}"可用於單選框或核取方塊的回顯
                若單選框的value和employee.gender的值一致,則新增checked="checked"屬性
			-->
            gender:<input type="radio" name="gender" value="1"th:field="${employee.gender}">male
            <input type="radio" name="gender" value="0"th:field="${employee.gender}">female<br>
            <input type="submit" value="update"><br>
        </form>
    </body>
</html>

具體功能:執行更新

控制器方法

@RequestMapping(value = "/employee", method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

歡迎關注公眾號:愚生淺末。

相關文章