当前位置:网站首页>07_ Springboot for restful style

07_ Springboot for restful style

2022-06-24 23:07:00 Book opens autumn maple

One 、 know RESTFul

REST( english :Representational State Transfer, abbreviation REST)

A style of Internet software architecture design , But it's not the standard , It just puts forward a set of The architecture concept and design principle of client and server interaction , The interface designed based on this concept and principle can More concise , More layers ,REST The word , yes Roy Thomas Fielding In his 2000 Proposed in the doctoral thesis of .

before : Access resources ( picture ,servlet Program ), Request resources with the request method , If get Request direct access to doget On the way , If post Request direct access to dopost

rest idea Access resources : Request resources , Then process it as requested , If it is get The way , Query operation , If it is put The way update operation , If it is delete The way Delete resources , If it is post The way Add resources .

Any technology can achieve this rest idea , If an architecture conforms to REST principle , Call it RESTFul framework

External embodiment :

For example, we are going to visit a http Interface :http://localhost:8080/boot/order?id=1021&status=1

Challenge parameters ?id=1021&status=1

use RESTFul style be http The address is :http://localhost:8080/boot/order/1021/1

Two 、Spring Boot Development RESTFul

Spring boot Development RESTFul It is mainly realized by several annotations

1. @PathVariable

obtain url Data in

The note is Realization RESTFul The most important comment

2. @PostMapping

Receive and process Post The way Request

​​​​​​​3. @DeleteMapping

receive delete The way Request , have access to GetMapping Instead of

​​​​​​​4. @PutMapping

receive put The way Request , It can be used PostMapping Instead of

​​​​​​​5. @GetMapping

receive get The way Request

3、 ... and 、​​​​​​​RESTful The advantages of

  • Light weight , Based on the direct http, There is no need for anything else, such as message protocol

get/post/put/delete by CRUD operation

  • Resources oriented , Be clear at a glance , Self explanatory .
  • Data description is simple , General with xml,json Do data exchange .
  • No state , Calling an interface ( visit 、 Operating resources ) When , You don't have to think about context , Regardless of the current state , It greatly reduces the complexity .
  • Simple 、 Low coupling

Four 、 Use RESTful style The simulation realizes the Additions and deletions operation  

​​​​​​​1.  establish RESTfulController, And write code

@RestController
public class RESTfulController {

    /*
     *  Add student 
     *  Request address :http://localhost:9094/004-springboot-springmvc/springBoot/student/suke/119
     *  Request mode :POST
     * @param name
     * @param age
     * @return
     * */
    @PostMapping(value = "/springBoot/student/{name}/{age}")
    public Object addStudent(@PathVariable("name") String name,
                             @PathVariable("age") Integer age) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("name", name);
        retMap.put("age", age);

        return retMap;
    }

    /*
     *  Delete students 
     *  Request address :http://localhost:9094/004-springboot-springmvc/springBoot/student/110
     *  Request mode :Delete
     *
     * @param id
     * @return
     * */
    @DeleteMapping(value = "/springBoot/student/{id}")
    public Object removeStudent(@PathVariable("id") Integer id) {

        return " Deleted students id by :" + id;
    }

    /*
     *  Modify student information 
     *  Request address :http://localhost:9094/004-springboot-springmvc/springBoot/student/120
     *  Request mode :Put
     *
     * @param id
     * @return
     * */
    @PutMapping(value = "/springBoot/student/{id}")
    public Object modifyStudent(@PathVariable("id") Integer id) {

        return " Modify the student's id by " + id;
    }

    @GetMapping(value = "/springBoot/student/{id}")
    public Object queryStudent(@PathVariable("id") Integer id) {

        return " Check the student's id by " + id;
    }
}

2.  Use Postman Simulate send request , To test

(1)@PostMapping(value = "/springBoot/student/{name}/{age}")

Add student
Request address :http://localhost:9004/004-springboot-springmvc/springBoot/student/ls/119
Request mode :POST

(2)@DeleteMapping(value = "/springBoot/student/{id}")

Delete students
Request address :http://localhost:9004/004-springboot-springmvc/springBoot/student/110
Request mode :Delete

(3)@PutMapping(value = "/springBoot/student/{id}")

Modify student information
Request address :http://localhost:9004/004-springboot-springmvc/springBoot/student/120
Request mode :Put

(4)@GetMapping(value = "/springBoot/student/{id}")

Search for student information
Request address :http://localhost:9004/004-springboot-springmvc/springBoot/student/123
Request mode :Get

(5) summary : In fact, the benefits we can feel here ​​​​​​​

It's easier to pass parameters

The service provider provides only one interface service , Not traditional CRUD Four interfaces

​​​​​​​3.  The problem of conflicting requests

  • Change path
  • Change the request mode

(1) establish RESTfulController class

/*
 * queryOrder1 and queryOrder2 The two request paths will conflict with each other 
 * queryOrder3 And queryOrder1 and queryOrder2 Requests do not conflict 
 *  Be careful : Although the way the two paths are written has changed , But because the two parameters passed are int value , So I don't know which request to send for processing 
 *       There will be an exception with ambiguous matching , So to resolve conflicts , There are two ways :
 *      1. Request to modify the path 
 *      2. Modify the request method 
 * */
@RestController
public class RESTfulController2 {

    @GetMapping(value = "/springBoot/order/{id}/{status}")
    public Object queryOrder(@PathVariable("id") Integer id,
                             @PathVariable("status") Integer status) {
        System.out.println("-----queryOrder--------");
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("id", id);
        map.put("status", status);

        return map;
    }

    @GetMapping(value = "/springBoot/{id}/order/{status}")
    public Object queryOrder1(@PathVariable("id") Integer id,
                              @PathVariable("status") Integer status) {
        System.out.println("-----queryOrder1--------");
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("id", id);
        map.put("status", status);

        return map;
    }

    @GetMapping(value = "/springBoot/{status}/order/{id}")
    public Object queryOrder2(@PathVariable("id") Integer id,
                              @PathVariable("status") Integer status) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("id", id);
        map.put("status", status);

        return map;
    }

    @PostMapping(value = "/springBoot/{status}/order/{id}")
    public Object queryOrder3(@PathVariable("id") Integer id,
                              @PathVariable("status") Integer status) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("id", id);
        map.put("status", status);

        return map;
    }
}

(2) combination Postman Conduct test instructions

@GetMapping(value = "/springBoot/order/{id}/{status}")

solve : Change path

@GetMapping(value = "/springBoot/{id}/order/{status}")

@GetMapping(value = "/springBoot/{status}/order/{id}")

Report errors : A request conflict has occurred

@PostMapping(value = "/springBoot/{status}/order/{id}")

solve : Change post Request mode

5、 ... and 、RESTful principle

① increase post request 、 Delete delete request 、 Change put request 、 check get request

② No verbs appear in the request path

for example : Query order interface

/boot/order/1021/1( recommend )

/boot/queryOrder/1021/1( Not recommended ) 

User/name/age/sex? page=1&sort=desc

③ Pagination 、 Sorting and other operations , You don't need to use slashes to pass parameters

for example : Order list interface

/boot/orders?page=1&sort=desc

Generally speaking Parameter is not a field of database table , You don't have to use slashes

④ REST:

  • Request resources
  • Request mode
  • Operate according to parameters
  • Information that is not a resource ( Parameters ), Generally do not use The slash passes the parameter , Use challenge parameters
原网站

版权声明
本文为[Book opens autumn maple]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241714023262.html