博客
关于我
SpringBoot Http getMapping、postMaping等详细解析
阅读量:545 次
发布时间: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/

你可能感兴趣的文章
OTA测试
查看>>
Outlook 2010 Inside Out
查看>>
overlay(VLAN,VxLAN)、underlay网络、大二层概述
查看>>
OWASP漏洞原理<最基础的数据库 第二课>
查看>>
OWL本体语言
查看>>
P with Spacy:自定义文本分类管道
查看>>
P1364 医院设置
查看>>
P2260 [清华集训2012]模积和
查看>>
SpringBoot中集成influxdb-java实现连接并操作Windows上安装配置的influxDB(时序数据库)
查看>>
SpringBoot中集成eclipse.paho.client.mqttv3实现mqtt客户端并支持断线重连、线程池高并发改造、存储入库mqsql和redis示例业务流程,附资源下载
查看>>
Padding
查看>>
paddlehub安装及对口罩检测
查看>>
SpringBoot中集成Actuator实现监控系统运行状态
查看>>
paddle的两阶段基础算法基础
查看>>
Page Object模式:为什么它是Web自动化测试的必备工具
查看>>
SpringBoot中重写addCorsMapping解决跨域以及提示list them explicitly or consider using “allowedOriginPatterns“ in
查看>>
PageHelper 解析及实现原理
查看>>
pageHelper分页工具的使用
查看>>
pageHelper分页技术
查看>>
PageHelper分页查询遇到的小问题
查看>>