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();
    }

相关推荐
星辰_mya6 分钟前
OSI 七层模型之“跨国诈骗集团”深度讲解
运维·服务器·后端·面试·架构师
实心儿儿1 小时前
Linux —— 基础IO - 文件描述符
linux·运维·服务器
clear sky .1 小时前
[linux]视频实时推流项目
linux·服务器·音视频
发光小北1 小时前
IEC104 转 Modbus TCP 网关如何应用?
网络·网络协议·tcp/ip
RisunJan2 小时前
Linux命令-nisdomainname(显示或设置系统的 NIS(Network Information Service)域名)
linux·运维·服务器
Wy_编程2 小时前
nginx测试
服务器·nginx
小此方2 小时前
Re:Linux系统篇(四)指令篇 · 三:两套打包压缩重要指令方法+剩余指令收尾
linux·运维·服务器
~ rainbow~2 小时前
前端转型全栈(六)——深入浅出:文件上传的原理与进阶
前端·http·文件上传
小宏运维有点菜2 小时前
服务器 BMC 管理 IP
服务器·tcp/ip·centos
isyangli_blog3 小时前
openstack 下载打包整套环境
服务器·网络·openstack