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

相关推荐
码农水水5 小时前
京东Java面试被问:HTTP/2的多路复用和头部压缩实现
java·开发语言·分布式·http·面试·php·wpf
GeekyGuru6 小时前
TCP/IP协议栈深度解析:从分层原理到内核实现与调优
网络·网络协议·tcp/ip
凯子坚持 c6 小时前
Protocol Buffers C++ 进阶数据类型与应用逻辑深度解析
java·服务器·c++
宴之敖者、6 小时前
Linux——权限
linux·运维·服务器
txinyu的博客7 小时前
MAC 地址
服务器·网络·macos
科技块儿8 小时前
【场景:识别C2通信】评估出站IP是否为已知恶意地址,方法:IP离线库+威胁情报融合
网络·网络协议·tcp/ip
咕噜签名-铁蛋8 小时前
火山云豆包:重新定义AI交互,让智能触手可及
服务器
安当加密9 小时前
电力系统如何防“明文传输”?某电网公司用SM2+UKey构建“端到端加密”实战
服务器·数据库·安全·阿里云
石像鬼₧魂石9 小时前
Kali Linux 内网渗透:深度工程实施手册
linux·运维·服务器
Ares-Wang9 小时前
网络》》IP组播
网络·网络协议·tcp/ip