RESTful

  • REST(Representational State Transfer):资源以某种表现形式在HTTP方法的作用下发生变化;

  • RESTful实践

    • 获取数据

      1
      GET "http://localhost:8080/rest/user/1" 

      定位id为1的用户(资源),用GET方法获取,查询资源;

    • 新增数据

      1
      2
      3
      4
      5
      6
      7
      POST "http://localhost:8080/rest/user"
      Content-Type:application/json
      {
      "name":"ming",
      "age":3,
      "email":"ming@test.com"
      }

      POST方法的参数通常会被放在请求体中,以Content-Type中的格式(JSON)提交到服务端;

    • 更新数据

      1
      2
      3
      4
      5
      6
      7
      8
      PUT "http://localhost:8080/rest/user"
      Content-Type:application/json
      {
      "id":1,
      "name":"ming",
      "age":21,
      "email":"ming@test.com"
      }

      与POST的区别在于请求参数还要指定一个唯一字段(如id);

    • 删除数据

      1
      DELETE "http://localhost:8080/rest/user/1" 
  • RESTful风格由URI定位资源

    • URI:Uniform Resource Identifier
    • URL:Uniform Resource Locator
    • URN:Uniform Resource Name

    所有的URLURN都可以称为URI

    URL可以定位资源,而URN不行;

spring 中的Restful应用

  • 接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    @RestController
    @Slf4j
    @RequestMapping("/user")
    public class UserController {

    @GetMapping
    public String hello(){
    return "hello";
    }

    @PostMapping
    public void userInfo1(@RequestBody User user){
    log.info(user.toString());
    }

    @PostMapping("/{age}")
    public void userInfo2(@PathVariable Integer age){
    System.out.println(age);
    }

    @PostMapping("/info")
    public void userInfo3(String name,Integer age){
    System.out.println(name+" "+age);
    }
    }
  • 请求方式

    1
    GET localhost:8888/user
    1
    2
    3
    4
    5
    6
    POST localhost:8888/user
    Content-Type:application/json
    {
    "name":"ming",
    "age":"20"
    }
  • 请求路径传参

    1
    POST localhost:8888/user/20
  • 普通路径传参

    1
    POST localhost:8888/user/info?name=ming&age=20