• Spring注解之处理常见的 HTTP 请求


    5 种常见的请求类型:

    • GET :请求从服务器获取特定资源。举个例子:GET /users(获取所有学生)
    • POST :在服务器上创建一个新的资源。举个例子:POST /users(创建学生)
    • PUT :更新服务器上的资源(客户端提供更新后的整个资源)。举个例子:PUT /users/12(更新编号为 12 的学生)
    • DELETE :从服务器删除特定的资源。举个例子:DELETE /users/12(删除编号为 12 的学生)
    • PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少

    GET 请求

    @GetMapping("users") 等价于@RequestMapping(value="/users",method=RequestMethod.GET)

    1. @GetMapping("/users")
    2. public ResponseEntity> getAllUsers() {
    3. return userRepository.findAll();
    4. }

     POST 请求

    @PostMapping("users") 等价于@RequestMapping(value="/users",method=RequestMethod.POST)

    关于@RequestBody注解的使用

    1. @PostMapping("/users")
    2. public ResponseEntity createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
    3.   return userRespository.save(user);
    4. }

     PUT 请求

    @PutMapping("/users/{userId}") 等价于@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)

    1. @PutMapping("/users/{userId}")
    2. public ResponseEntity updateUser(@PathVariable(value = "userId") Long userId,
    3.   @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
    4.   ......
    5. }

    DELETE 请求

    @DeleteMapping("/users/{userId}")等价于@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)

    1. @DeleteMapping("/users/{userId}")
    2. public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
    3.   ......
    4. }

    PATCH 请求

    一般实际项目中,我们都是 PUT 不够用了之后才用 PATCH 请求去更新数据。

    1. @PatchMapping("/profile")
    2.   public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
    3.         studentRepository.updateDetail(studentUpdateRequest);
    4.         return ResponseEntity.ok().build();
    5.     }

  • 相关阅读:
    VUE3照本宣科——应用实例API与setup
    MySQL基础篇【聚合函数】
    计算机毕业设计 基于SpringBoot智慧养老中心管理系统的设计与实现 Javaweb项目 Java实战项目 前后端分离 文档报告 代码讲解 安装调试
    黑马JVM总结(三)
    03-3.1.3 栈的链式存储的实现
    2022杭电多校第一场题解
    【891. 子序列宽度之和】
    数据库——理论基础
    anaconda python 版本对应关系
    「MacOS」Swift 第一章:基础部分
  • 原文地址:https://blog.csdn.net/weixin_62988359/article/details/136327299