博客
关于我
SpringBoot Http getMapping、postMaping等详细解析
阅读量:535 次
发布时间:2019-03-09

本文共 2029 字,大约阅读时间需要 6 分钟。

背景

在开发Spring Boot项目时,对于HTTP请求在Controller层的处理方式一直让人望而却步。于是我决定通过实际项目实践和测试,总结这些方法的应用场景和用法。

项目环境:

  • Spring Boot 2.3.4
  • Swagger 2.9.2

依赖项:

org.springframework.boot
spring-boot-starter
2.3.4.RELEASE

参数处理

主要注解

@GetMapping

用于 GET 请求,通常用于查询资源。在 RESTful 设计中,路径参数被称为 @PathVariable。

@GetMapping("/get/{id}")public ResponseEntity
getUser(@PathVariable int id) { // TODO组织用户业务逻辑}

@PostMapping

用于 POST 请求,通常用于添加资源。适合接收多个参数,包括文件。

@PostMapping("/post/user")public ResponseEntity
createUser(@RequestBody User user) { // 具体业务逻辑}

@RequestParam

用于查询字符串参数,适用于 不是payload 的数据。

@RequestParam(name = "name") String name

@RequestBody

用于接收 JSON 格式的数据。默认内容类型为application/json。

@PostMapping("/post/user")public ResponseEntity
createUser(@RequestBody User user) { // 具体业务逻辑}

@RequestPart

用于多部分内容(file upload),需要使用 MultipartEntity。

@PostMapping("/post/user")public ResponseEntity
createUser(@RequestPart User user, @RequestPart MultipartFile file) { // 具体业务逻辑}

路径参数与请求参数

路径参数使用 @PathVariable 注解,根据 URL 地址书写在路径中。请求参数使用 @RequestParam 使用查询字符串。

文件上传

使用 @RequestPart 注解,传递文件参数和其他 DTO。

@PostMapping("/post/user")public ResponseEntity
createUser(@RequestPart User user, @RequestPart MultipartFile file) { // 具体业务逻辑}

查询式请求

通常使用 GET 请求,适用于只读操作。

@GetMapping("/user/{id}")public ResponseEntity
getUser(@PathVariable int id) { // 组织用户业务逻辑}

新增式请求

Post 请求新增资源,通常是添加用户或其他实体。

@PostMapping("/用户")public ResponseEntity
createUser(@RequestBody User user) { // 具体业务逻辑写在这里}

修改式请求

Put 请求用于更新资源。

@PutMapping("/用户/{id}")public ResponseEntity
updateUser(@PathVariable int id, @RequestBody User user) { // 具体业务逻辑}

删除式请求

Delete 请求用于删除资源,通常会带路径参数或 DTO。

@DeleteMapping("/用户/{id}")public ResponseEntity
deleteUser(@PathVariable int id) { // 具体业务逻辑}

总结

通过这些测试,我理解了 @PostMapping、@GetMapping 等注解在不同场景下的应用。每个注解都有其适合的使用场景和限制。例如,@RequestBody 通常用于接收 JSON 格式的数据,而 @RequestPart 更适合文件上传或与多个数据相关的场景。

虽然我还需要进一步学习一些高级功能,比如参数校验和异常处理,但通过这些实践,我对Spring Boot Controller 中的HTTP请求处理有了更深入的理解。

转载地址:http://neusz.baihongyu.com/

你可能感兴趣的文章
痞子衡嵌入式:分享一个i.MXRT系列配套DRAM压力测试上位机工具(i.MXRT DRAM Tester)...
查看>>
Mysql-缓存
查看>>
09-【继承、抽象类】
查看>>
25-【JDBC】
查看>>
Struts2-从值栈获取list集合数据(三种方式)
查看>>
LeetCode 两数之和
查看>>
98-对选择排序算法的实现和分析
查看>>
101-浅谈指针
查看>>
134-C++学习第八弹(重载)
查看>>
154-删除链表中重复元素(只保留出现一次的元素)
查看>>
254-Redis(关于hiredis)
查看>>
286-Go语言的操作符
查看>>
LeetCode刷题记录12——232. Implement Queue using Stacks(easy)
查看>>
nginx刷新出现nginx404
查看>>
PAT
查看>>
vue-axios的总结及项目中的常见封装方法。
查看>>
单例模式的python实现
查看>>
【docker】开启remote api访问,并使用TLS加密
查看>>
MySQL 一些小知识
查看>>
JUC并发学习笔记
查看>>