RESTful style of spring MVC learning notes

7 use spring MVC to complete the implementation of RESTful

7.1 what is RESTful style?

REST: Representational State Transfer, the state transfer of presentation layer resources. It is a style of resource positioning and resource operation. It's not a standard or agreement, it's just a style. The software designed based on this style can be more concise, more hierarchical, and easier to implement caching and other mechanisms.

**Definition of resources: * * all things on the Internet can be abstracted as resources.
**State transition: * * transfer between client and server represents the expression of resource state. Through the expression of transfer and operation resources, the purpose of operating resources can be realized indirectly.
Resource operation: there are four methods: POST, DELETE, PUT and GET. Different methods are used to operate resources (add, DELETE, modify and query)

7.2 comparison between traditional style and RESTFul style

7.2.1 using traditional style to operate resources

Different effects can be achieved through different parameters! Single method!

http://127.0.0.1/item/queryItem?id=1 (query, GET)
http://127.0.0.1/item/saveItem (new, POST)
http://127.0.0.1/item/updateItem (update, POST)
http://127.0.0.1/item/deleteItem?id=1 (delete, GET or POST)

7.2.2 using RESTful style to operate resources

Different effects can be achieved through different request methods!
As follows: the request address is the same, but the function can be different!

http://127.0.0.1/item/1 (query, GET)
http://127.0.0.1/item (new, POST)
http://127.0.0.1/item (update, PUT)
http://127.0.0.1/item/1 (DELETE)

7.3 HiddenHttpMethodFilter

Since the browser only supports sending get and post requests, how to send put and delete requests?

Spring MVC provides HiddenHttpMethodFilter to help us convert POST requests into DELETE or PUT requests

HiddenHttpMethodFilter conditions for processing put and delete requests:

  • The request method of the current request must be post (send the post request through form or ajax)

  • The current request must transmit the request parameters_ method

If the above conditions are met, the HiddenHttpMethodFilter filter will convert the request mode of the current request into request parameters_ Method, so the request parameter_ The method value is the final request method

On the web Register HiddenHttpMethodFilter in XML

<filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Note:
So far, spring MVC has provided two filters: characterencoding filter and HiddenHttpMethodFilter
On the web When registering in XML, you must first register CharacterEncodingFilter and then HiddenHttpMethodFilter
reason:

  • Pass request. In characterencoding filter The SetCharacterEncoding (encoding) method sets the encoding of the character set
  • request. The SetCharacterEncoding (encoding) method requires that there must be no previous operation to obtain the request parameters
  • HiddenHttpMethodFilter has exactly one operation to obtain the request method:
    String paramValue = request.getParameter(this.methodParam);

7.4 RESTful cases

Case Objective: like traditional CRUD, it can add, delete, modify and query employee information.

7.4.1 preparation

  1. Build a new project

  2. Prepare entity class

    public class Employee {
    
       private Integer id;
       private String lastName;
    
       private String email;
       //1 male, 0 female
       private Integer gender;
       
       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 Employee(Integer id, String lastName, String email, Integer gender) {
          super();
          this.id = id;
          this.lastName = lastName;
          this.email = email;
          this.gender = gender;
       }
    
       public Employee() {
       }
    }
    
  3. Prepare dao simulation data

    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.zjw.mvc.bean.Employee;
    import org.springframework.stereotype.Repository;
    
    
    @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 there is no ID, it is assigned automatically
          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);
       }
    }
    

7.4.2 function list

7.4.3 specific functions: visit the home page

  1. Configure view controller

    <mvc:view-controller path="/" view-name="index"/>
    
  2. Create page

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" >
        <title>Title</title>
    </head>
    <body>
    <h1>home page</h1>
    <a th:href="@{/employee}">Access employee information</a>
    </body>
    </html>
    

7.4.4 specific function: query all employee data

  1. Controller method

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String getEmployeeList(Model model){
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList", employeeList);
        return "employee_list";
    }
    
  2. Create 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>
    
  3. Result display:

7.4.5 specific functions: delete

  1. On the web HiddenHttpMethodFilter is introduced after the encoding processor in XML
      <!--Configure how requests are processed put and delete of HiddenHttpMethodFilter-->
         <filter>
             <filter-name>HiddenHttpMethodFilter</filter-name>
             <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
         </filter>
         <filter-mapping>
             <filter-name>HiddenHttpMethodFilter</filter-name>
             <url-pattern>/*</url-pattern>
         </filter-mapping>
  1. Create a form that handles the delete request

    <!-- Function: control the submission of forms through hyperlinks post Request converted to delete request -->
    <form id="delete_form" method="post">
        <!-- HiddenHttpMethodFilter Requirement: must be transmitted_method Request parameters, and the value is the final request method -->
        <input type="hidden" name="_method" value="delete"/>
    </form>
    
  2. Delete hyperlink binding click event

    Introduce Vue js

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


    Delete hyperlink

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

    Handling click events through vue

    <script type="text/javascript">
        var vue = new Vue({
            el:"#dataTable",
            methods:{
                //Event indicates the current event
                deleteEmployee:function (event) {
                    //Get form label by id
                    var delete_form = document.getElementById("delete_form");
                    //Assign the href attribute of the hyperlink that triggers the event to the action attribute of the form
                    delete_form.action = event.target.href;
                    //Submit Form 
                    delete_form.submit();
                    //Block default jump behavior of hyperlinks
                    event.preventDefault();
                }
            }
        });
    </script>
    
  3. Controller method

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

7.4.6 specific functions: adding data

  1. Configure view controller

    <mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>
    
  2. Create add user page 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>
    
  3. Controller method

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

7.4.7 specific functions: jump to the update data page

  1. Modify hyperlink
<a th:href="@{'/employee/'+${employee.id}}">update</a>
  1. Controller method
@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";
}
  1. Create 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}"Can be used for echo of radio boxes or check boxes
            If the radio box is value and employee.gender If the values are consistent, add checked="checked"attribute
        -->
        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>
    

7.4.8 execute update

Controller method

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

Keywords: Java Back-end RESTful

Added by Swedie on Fri, 07 Jan 2022 08:24:47 +0200