一、四大请求引入

1、GET 请求
  1. 通常用于请求资源

  2. 通常在路径中带参

  3. 在 Spring Boot 中,使用 @GetMapping@RequestMapping(method = RequestMethod.GET) 注解来映射请求方式与请求路径

  4. 使用 @RequestParam 来映射请求参数

2、POST 请求
  1. 通常用于提交资源

  2. 通常在请求体中带参

  3. 在 Spring Boot 中,使用 @PostMapping@RequestMapping(method = RequestMethod.POST) 注解来映射请求方式与请求路径

  4. 使用 @RequestBody 来映射请求体

3、PUT 请求
  1. 通常用于修改资源

  2. 通常在路径中带参

  3. 在 Spring Boot 中,使用 @PutMapping@RequestMapping(method = RequestMethod.GET) 注解来映射请求方式与请求路径

  4. 使用 @RequestBody 来映射请求体

4、DELETE 请求
  1. 通常用于删除资源

  2. 通常在请求体中带参

  3. 在 Spring Boot 中,使用 @DeleteMapping@RequestMapping(method = RequestMethod.DELETE) 注解来映射请求方式与请求路径

  4. 使用 @RequestParam 来映射请求参数


二、四大请求基本使用

0、控制器
  1. 在 Spring Boot 中,使用 @Controller 注解定义控制器,使用 @ResponseBody 注解定域返回值作为响应主体内容

  2. 但这两个注解可以同时用一个注解 @RestController 代替,这里我推荐写少不写多

  3. 使用 @RequestMapping 注解来映射请求基础路径

@Controller
@ResponseBody
@RequestMapping("/myTest")
public class MyTestController {}
// 推荐这种写法

@RestController
@RequestMapping("/myTest")
public class MyTestController {}
1、GET 请求
(1)不带参
  • 返回一个Staff 对象实例
@GetMapping("/testGet")
public Staff testGet() {
    Staff staff = new Staff(1, "jack", 10);

    return staff;
}
(2)带参
  • 根据请求参数 id,从 Map 中返回对应的 Staff 对象
@GetMapping("/testGetCarryData")
public Staff testGetCarryData(@RequestParam("id") Integer id) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    return staffMap.get(id);
}
2、POST 请求
  • 根据请求体 TestPostDTO 中的 id,从 Map 中返回对应的 Staff 对象
@PostMapping("/testPost")
public Staff testPost(@RequestBody TestPostDTO testPostDTO) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    return staffMap.get(testPostDTO.getId());
}
3、PUT 请求
  • 根据请求体 TestPutDTO 中的 id,找到对应的 Staff 对象,更新其年龄
@PutMapping("/testPut")
public String testPut(@RequestBody TestPutDTO testPutDTO) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    Staff staff = staffMap.get(testPutDTO.getId());
    staff.setAge(testPutDTO.getAge());

    return "testPut OK";
}
4、DELETE 请求
  • 根据请求参数 id,从 Map 中返回删除的 Staff 对象
@DeleteMapping("/testDelete")
public String testDelete(@RequestParam("id") Integer id) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    staffMap.remove(id);

    return "testDelete OK";
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部