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

相关推荐
GhostGuardian21 分钟前
DNS报文结构全解析
网络·网络协议
su31729 分钟前
rap2部署
linux·运维·服务器
宁雨桥1 小时前
WebSocket 完全指南:从原理到实战,搭建实时通信桥梁
网络·websocket·网络协议
xinxinhenmeihao1 小时前
爬虫导致IP被封号了如何解封?
爬虫·网络协议·tcp/ip
skywalk81631 小时前
阿里云服务器FreeBSD新系统从登录、配置到升级:从14.1升级到FreeBSD 14.3 Release
linux·服务器·阿里云·freebsd
草莓熊Lotso1 小时前
Linux 基础开发工具入门:软件包管理器的全方位实操指南
linux·运维·服务器·c++·人工智能·网络协议·rpc
拾忆,想起1 小时前
TCP滑动窗口:网络世界的“智能流量阀门”
java·网络·数据库·网络协议·tcp/ip·php·哈希算法
木木em哈哈1 小时前
有关于cnb自动化的脚本补全
服务器·开发语言·pygame
Mr_Xuhhh1 小时前
GUI自动化测试--自动化简单示例
运维·服务器·自动化
羑悻的小杀马特1 小时前
零成本自建私人知识库教学,Leanote+Cpolar 内网穿透,手机电脑随时同步,无需云服务器,效率翻倍!
运维·服务器·coplar·leanote