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

相关推荐
北京盟通科技官方账号18 分钟前
工业通讯底层对齐:EtherNet/IP Class 1 连接中的 32-bit Header 与内存映射逻辑
服务器·网络·网络协议·自动化·制造
lengjingzju1 小时前
一网打尽Linux IPC(三):System V IPC
linux·服务器·c语言
SoveTingღ3 小时前
【问题解析】我的客户端与服务器交互无响应了?
服务器·c++·qt·tcp
zhougl9963 小时前
Vuex 模块命名冲突:问题解析与完整解决方案
linux·服务器·apache
爱丽_4 小时前
MyBatis动态SQL完全指南
服务器·sql·mybatis
I · T · LUCKYBOOM4 小时前
1.Apache网站优化
linux·运维·服务器·网络·apache
GHL2842710905 小时前
vmware中无法看到共享文件夹
linux·运维·服务器
我是伪码农5 小时前
注册表单提交加验证码功能
运维·服务器
GanGuaGua5 小时前
JsonRpc:手搓一个高性能Rpc服务(应用篇)
qt·网络协议·rpc
盛世宏博北京6 小时前
从服务器机房到 IDC 集群:网口温湿度变送器的全场景适配监控
运维·服务器