1. 程式人生 > >【SpringMVC】7.REST風格的CRUD實戰(一)之前期工作

【SpringMVC】7.REST風格的CRUD實戰(一)之前期工作

一、什麼是REST和CRUD?

1.有關REST

有關REST的解釋我已近在之前的SpringMVC系列文章提到過,如果有興趣的同學可以翻看《【SpringMVC】3.REST表現層狀態轉換》進行檢視。

2.有關CRUD

In computer programming, create, read, update, and delete(CRUD) are the four basic functions of persistent storage.Alternate words are sometimes used when defining the four basic functions of CRUD, such as retrieve instead of read, modify instead of update, or destroy instead of delete. CRUD is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information; often using computer-based forms and reports. The term was likely first popularized by James Martin in his 1983 book Managing the Data-base Environment.[1][3] The acronym may be extended to CRUDL to cover listing of large data sets which bring additional complexity such as pagination when the data sets are too large to hold easily in memory.–

維基百科《Create, read, update and delete》

在計算機程式設計中,建立,讀取,更新和刪除CRUD)是持久儲存的四個基本功能。在定義CRUD的四個基本功能時,有時會使用替代詞,例如檢索而不是讀取,修改而不是更新,或者銷燬而不是刪除。CRUD有時也用於描述便於檢視,搜尋和更改資訊的使用者介面約定; 經常使用基於計算機的表格和報告。詹姆斯·馬丁(James Martin)在其1983年的“ 管理資料庫環境”一書中首次推廣該術語。首字母縮略詞可以擴充套件到CRUDL,以涵蓋大資料集的列表,當資料集太大而無法輕易儲存在記憶體中時,這些資料集會帶來額外的複雜性,例如分頁。

二、實戰專案需求

1.目標

使用RESTCRUD的方式來對資料進行增加,查詢,修改,刪除操作。

2.相關介面

顯示所有員工資訊

  • URI:emps
  • 請求方式:GET
  • 顯示效果 這裡寫圖片描述

顯示新增頁面

  • URI:emp
  • 請求方式:GET
  • 顯示效果 這裡寫圖片描述

新增員工資訊

  • URI:emp
  • 請求方式:POST
  • 顯示效果:完成新增,重定向到 list 頁面。

刪除操作

  • URL:emp/{id}
  • 請求方式:DELETE
  • 刪除後效果:對應記錄從資料表中刪除

修改操作

  • 顯示修改頁面
  • URI:emp/{id}
  • 請求方式:GET
  • 顯示效果:回顯表單。

修改員工資訊

  • URI:emp
  • 請求方式:PUT
  • 顯示效果:完成修改,重定向到 list 頁面

三、實戰程式碼

開發前需要準備的配置

1.建立一個名為SpringMVC-2的新Web專案

2.匯入相關的JAR包

這裡寫圖片描述

3.配置web.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <!-- 配置springDispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

4.配置src根目錄下的springmvc.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <!-- 配置自動掃描的包 -->
    <context:component-scan base-package="com.springmvc.crud"></context:component-scan>

    <!-- 配置檢視解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

5.在com.springmvc.crud.entities包中建立實體類EmployeeDepartment

實體類Employee

package com.springmvc.crud.entities;

import java.util.Date;

import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

public class Employee {

    private Integer id;
    @NotEmpty
    private String lastName;

    @Email
    private String email;
    //1 male, 0 female
    private Integer gender;

    private Department department;

    @Past
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;

    @NumberFormat(pattern="#,###,###.#")
    private Float salary;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Float getSalary() {
        return salary;
    }

    public void setSalary(Float salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", lastName=" + lastName + ", email="
                + email + ", gender=" + gender + ", department=" + department
                + ", birth=" + birth + ", salary=" + salary + "]";
    }

    public Employee(Integer id, String lastName, String email, Integer gender,
            Department department) {
        super();
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
    }

    public Employee() {
        // TODO Auto-generated constructor stub
    }
}

實體類Department

package com.springmvc.crud.entities;

public class Department {

    private Integer id;
    private String departmentName;

    public Department() {
        // TODO Auto-generated constructor stub
    }

    public Department(int i, String string) {
        this.id = i;
        this.departmentName = string;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    @Override
    public String toString() {
        return "Department [id=" + id + ", departmentName=" + departmentName
                + "]";
    }

}

6.在com.springmvc.crud.dao中建立Dao類EmployeeDaoDepartmentDao

注意!!! 由於由於連線資料庫比較麻煩,所以在這裡選擇使用靜態模擬從資料庫中取出資料。

Dao類EmployeeDao

package com.springmvc.crud.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.springmvc.crud.entities.Department;
import com.springmvc.crud.entities.Employee;

@Repository
public class EmployeeDao {

    private static Map<Integer, Employee> employees = null;

    @Autowired
    private DepartmentDao departmentDao;

    static{
        employees = new HashMap<Integer, Employee>();

        employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
        employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
        employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
        employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
        employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE")));
    }

    private static Integer initId = 1006;

    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }

        employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
        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);
    }
}

Dao類DepartmentDao

package com.springmvc.crud.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.springmvc.crud.entities.Department;

@Repository
public class DepartmentDao {

    private static Map<Integer, Department> departments = null;

    static{
        departments = new HashMap<Integer, Department>();

        departments.put(101, new Department(101, "D-AA"));
        departments.put(102, new Department(102, "D-BB"));
        departments.put(103, new Department(103, "D-CC"));
        departments.put(104, new Department(104, "D-DD"));
        departments.put(105, new Department(105, "D-EE"));
    }

    public Collection<Department> getDepartments(){
        return departments.values();
    }

    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}

7.在WebRoot/WEB-INF/views/下建立list.jspinput.jsp

8.在WebRoot根目錄建立index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>

  <body>
   <a href="emps">Show all employee</a>


  </body>
</html>

9.在com.springmvc.crud.handlers下建立Handler類EmployeeHandler