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)

java 复制代码
@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
    return userRepository.findAll();
}

POST 请求

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

关于@RequestBody注解的使用

java 复制代码
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
     return userRespository.save(user);
}

PUT 请求

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

java 复制代码
@PutMapping("/users/{userId}")
public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId,
  @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
  ......
}

DELETE 请求

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

java 复制代码
@DeleteMapping("/users/{userId}")
public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
  ......
}

PATCH 请求

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

java 复制代码
 @PatchMapping("/profile")
  public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
        studentRepository.updateDetail(studentUpdateRequest);
        return ResponseEntity.ok().build();
    }

相关推荐
青山是哪个青山17 分钟前
Linux 基础与环境搭建
linux·服务器·网络
Codefengfeng1 小时前
linux系统安装软件教程
linux·运维·服务器
杜子不疼.5 小时前
UU云电脑深度测评:高性价比游戏云电脑,办公版本即将推出
服务器·游戏·电脑
袁袁袁袁满8 小时前
Linux云服务器如何判断系统是否发生过异常断电?
linux·运维·服务器
如若12311 小时前
AutoDL云服务器 NVIDIA 570驱动 EGL渲染修复全记录
运维·服务器·python
晚秋大魔王11 小时前
泰拉瑞亚手机版服务器部署
运维·服务器·泰拉瑞亚
敲代码的哈吉蜂11 小时前
高可用集群Keepalived
运维·服务器·网络·数据库
青衫码上行11 小时前
【项目部署】Spring Boot项目部署的四种方式
java·linux·服务器·spring boot·后端·docker·腾讯云
盟接之桥12 小时前
盟接之桥说制造:从客供的外在共生到内在的身心合一
运维·服务器·网络·人工智能·制造
林姜泽樾13 小时前
linux入门第四章,cd指令和相对、绝对路径
linux·运维·服务器