兜兜零元 发表于 2022-6-25 07:18:19

REST风格介绍、restful使用案例

目录
一 REST风格介绍
二 案例

一 REST风格介绍


REST风格:就是访问网络资源的格式
REST : Representational State Transfer (表现形式状态转换)
优点:
    隐藏了访问行为
    书写简化
https://img-blog.csdnimg.cn/b08f1e9b6ddb43efa6803717e34584a4.png
    
通过路径 + 访问方式 即可知道 访问行为
但如下的访问方式和路径不是必须的约束,是可以打破的(但99%都按照rest风格写了)
注意:路径里模块的名称通常使用复数
restful:根据rest风格对资源进行访问叫做restful
restful开发:就是你要用rest风格进行开发
 
https://img-blog.csdnimg.cn/495c76fe2b46490a86df720c3c216041.png
二 案例

操作 访问方式  访问路径
增    POST    http://localhost:8080/users
删    DELETE  http://localhost:8080/users/1
改    PUT     http://localhost:8080/users
查一    GET    http://localhost:8080/users/1
查所有 GET   http://localhost:8080/users
要点:
1 设定http请求动作(访问方式):@PostMapping、@DeleteMapping、@PutMapping、@GetMapping
2 设定请求参数(访问路径):形参上加@PathVariable注解,路径上要有参数的占位
备注:
@RestController = @Controller + @ResponseBody
@PostMapping = @RequestMapping(method = RequestMethod.POST)
代码
package com.qing.controller;

import com.qing.domain.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    //增        POST        http://localhost:8080/users
    @PostMapping
    public String save(User user) {
      System.out.println("save success"+user);
      return "save success";
    }

    //删        DELETEhttp://localhost:8080/users/1
    //@PathVariable : 用于绑定url的占位符,restful风格
    @DeleteMapping("/{id}")
    public String detete(@PathVariable Integer id) {
      System.out.println("detete " + id + " success");
      return "detete " + id + " success";
    }

    //改        PUT   http://localhost:8080/users
    @PutMapping
    public String update(User user) {
      System.out.println("update success");
      return "update success";
    }

    //查一        GET    http://localhost:8080/users/1
    @GetMapping("/{id}")
    public String selectById(@PathVariable Integer id) {
      System.out.println("selectById " + id + " success");
      return "selectById " + id + " success";
    }

    //查所有 GET   http://localhost:8080/users
    @GetMapping
    public String selectAll() {
      System.out.println("selectAll success");
      return "selectAll success";
    }


} 测试工具postman下载路径

 测试结果
https://img-blog.csdnimg.cn/66ded2d08af14116a2f1d407dc680110.png
 https://img-blog.csdnimg.cn/527a0e0aa6ca4c9c87a52bf2f1bf2fc1.png
 https://img-blog.csdnimg.cn/a858972246cd435bbc65faad9e804c30.png
 https://img-blog.csdnimg.cn/5b767896f05a4752ae4957ddb50d2a3f.png
 https://img-blog.csdnimg.cn/a1e8961434f94f2b9115706241707931.png


https://img-blog.csdnimg.cn/9925638a34ab4c81a5e3d6f78f17fd43.png


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: REST风格介绍、restful使用案例