RESTful allows you to define interfaces gracefully

Source of resources: https://www.bilibili.com/video/BV1et411T7SS You can follow the teacher and speak well.

Combine this picture to understand RESTful:

=====================================================I. RESTful first acquaintance================================================

REST([Resource] Representational State Transfer): state transformation of presentation layer
REST refers to a set of architectural constraints and principles. Applications or designs that meet these constraints and principles are RESTful


Based on the above explanation, let's summarize what is RESTful architecture:
(1) Each URI represents a resource;
(2) Between the client and the server, transfer some kind of presentation layer of this resource;
(3) Through the unified interface provided by HTTP, the client operates the server-side resources to realize "the state transformation of the presentation layer (using HTTP verbs to promote the server-side resources)".

=======================================================2, RESTful design================================================

1. Resource design

In the RESTful architecture, each web address represents a resource, so there can be no verbs but nouns in the web address, and the nouns often correspond to the table name of the database. Generally speaking, "collection" should be the plural noun in the database.

Description: v1: is the version number. Purpose: it can facilitate product upgrading

https://api.example.com/v1/zoos: Zoo resources
https://api.example.com/v1/animals: Animal Resources
https://api.example.com/v1/employees: breeder resources

2. Action settings

Expose resources according to the semantics of HTTP methods. There are these actions:

GET (SELECT): fetch resources (one or more items) from the server.
POST (CREATE): CREATE a new resource on the server.
PUT (UPDATE): UPDATE resources on the server (the client provides the changed complete resources).  
DELETE (DELETE): deletes resources from the server.

3. Return results

For the above actions, we can set the corresponding code flag to complete or exception handling when the processing is completed

Refer to this blog: https://www.cnblogs.com/nosqlcoco/p/5562107.html

The HttpServletResponse class also has corresponding constants. For example:

public static final int SC_OK = 200;

public static final int SC_CREATED = 201;

public static final int SC_ACCEPTED = 202;
https://api.example.com/v1/employees for this resource path, it is designed according to spring MVC

@RequestMapping("v1/employees")
@RestController   
public class EmployeeController {

    @GetMapping//4.3 later versions  
    public List<Employee> list(){
       //Specify the GET method to GET the resource
    }

    @PostMapping("{employeeId}/salaries")
    public Salary addOneSalary(Salary salary){
       //Add a salary record to the employee
    } 
    
    @PutMapping("{id}")
    public void update(Employee employee){
       //Update an employee record. When sending a request using ajax, the httpPutFormContentFilter filter is used to process the request
                            Otherwise, the parameters sent will be null
       /* Set a filter httpPutFormContentFilter when processing the put patch request
       * HttpPutFormContentFilter The filter will automatically encapsulate the parameters of the PUT request passed from the foreground,
       * If the HttpPutFormContentFilter filter is not configured, tomcat will not automatically encapsulate the parameters of PUT requests 
       * Count.*/
       
    }   
    @DeleteMapping("{id}")
    public void delById(@PathVariable("id") Long id, HttpServletResponse response){
        //Delete a record
    }
}

 

=======================================================3, RESTful service development================================================

To develop RESTful services using spring MVC, let's explain some common annotations of spring MVC.

1. @ Controller, @ RestController, @ ResponseBody

The RestController interface inherits the Controller interface and also injects the ResponseBody annotation. Therefore, in the data acquisition of a single page, we can directly mark the RestController annotation in this class, which is very convenient.

2. @ RequestMapping , contains restful style action annotations

--------@GetMapping   

@ GetMapping @ is equivalent to @ RequestMapping(value = "employees",method = RequestMethod.GET), and others are similar.

--------@PatchMapping 

patch mode is a supplement to put mode; The put mode can be updated But the update is the whole patch is a local update;

Note: Spring MVC sets a filter httpPutFormContentFilter for put and patch requests sent by ajax, as mentioned above.

  <!--  HttpPutFormContentFilter Filter pair put patch Request parameters for processing-->
  <filter>
    <filter-name>httpPutFormContentFilter</filter-name>
    <!--  The filtered address we wrote   -->
    <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>httpPutFormContentFilter</filter-name>
    <servlet-name>springmvc</servlet-name>
  </filter-mapping>

---------@PutMapping,@PostMapping

Our common requests are post and get, while REST style URL s and put and delete requests correspond to the CURD of the database. Normal browsers only support post and get. In this case, the HiddenHttpMethodFilter filter is required to convert post requests into put and delete requests.

Send put request in the form of from form

For forms method only post,get Therefore, we need to do some processing to set the hidden submission method put request
<form action="/employees/1" method="post">
    <input type="hidden" name="_method" value="put">
    <input name="name" type="text"/><!-- Hide the submission method. In fact, what is submitted is put -->
    <button>Submit</button>
</form>
HiddenHttpMethodFilter filter to convert post requests into put and delete requests_ Attribute defined by method Interceptor: private String methodParam = "_method";
  <filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <!--  The filtered address we wrote   -->
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <servlet-name>springmvc</servlet-name>
  </filter-mapping>

3. Parameterization of @ RequestMapping


For details, see: https://blog.csdn.net/weixin_43453386/article/details/83419060 

4,@PathVariable 

Map the placeholder bound by the URL. The placeholder parameter in the URL can be bound to the input parameter of the controller processing method through @ PathVariable: the {xxx} placeholder in the URL can be

@PathVariable("xxx") is bound to the input parameter of the operation method. For example:

   /*
    *     @JsonFormat(pattern = "yyyy-mm-dd",timezone = "GEM+8")  :Annotation of the time returned from the background to the foreground
    */
    @GetMapping("{employeeId}/salaries/{month}")
    public Salary getSalary(@PathVariable Long employeeId,@PathVariable             
                                    @DateTimeFormat(pattern = "yyyy-mm-dd") Date month){
        return  new Salary(1l,employeeId, BigDecimal.TEN,month);
    }
 

Keywords: REST RESTful

Added by dandelo on Tue, 08 Mar 2022 16:47:54 +0200