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

相关推荐
byte轻骑兵6 分钟前
【HIDS】规范精讲[2]:一枚 Report 的诞生——HID 服务端特征全解剖
网络协议·人机交互·低功耗蓝牙·蓝牙协议·hogp
服务器硬件项目经理14 分钟前
第5章消费级vs专业级vs数据中心:显卡的门派
服务器·嵌入式硬件·gru·硬件工程·硬件
邪修king17 分钟前
Re:Linux系统篇(三十六):进程间通信Chapter3:从匿名管道到命名管道:Linux 进程间通信实战(FIFO 深度解析)
linux·运维·服务器
Rabitebla24 分钟前
【Linux】 权限篇(三):深入理解 umask 位运算与粘滞位的设计思想
java·linux·服务器·c++·笔记·学习
Tech探索者28 分钟前
重装飞牛 NAS,几 KB 的 .bin 够吗?我的备份与恢复全过程
运维·服务器
讯捷蓝达39 分钟前
机房突发断电,5 盘 RAID硬盘全部掉线: 急速上门救援,现场4小时华为2288H V5服务器数据完整恢复
运维·服务器·数据库
ly76891 小时前
性能剖析与压测方法论:JMH、async-profiler 与分层瓶颈定位的可复现实验
服务器·前端·数据库·压测·jmh·性能剖析·async-profiler
风翼靓崽1 小时前
磁盘逻辑卷扩容
linux·运维·服务器
Brilliantwxx1 小时前
【STM32】RTC 完结篇:日期操作、闹钟中断与附录(时间戳 / 闹钟 / NTP)
服务器·c语言·stm32·单片机·嵌入式硬件·实时音视频
zincsweet1 小时前
Linux网络编程入门(二):从 UDP 回显服务器到多人聊天室,三个项目的渐进式实践
linux·服务器·网络