博客
关于我
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/

你可能感兴趣的文章
Openlayers中使用Cluster实现缩放地图时图层聚合与取消聚合
查看>>
Openlayers中使用Image的rotation实现车辆定位导航带转角(判断车辆图片旋转角度)
查看>>
Openlayers中加载Geoserver切割的EPSG:900913离线瓦片图层组
查看>>
Openlayers中多图层遮挡时调整图层上下顺序
查看>>
Openlayers中将某个feature置于最上层
查看>>
Openlayers中点击地图获取坐标并输出
查看>>
Openlayers中设置定时绘制和清理直线图层
查看>>
Openlayers图文版实战,vue项目从0到1做基础配置
查看>>
Openlayers实战:modifystart、modifyend互动示例
查看>>
Openlayers实战:判断共享单车是否在电子围栏内
查看>>
Openlayers实战:加载Bing地图
查看>>
Openlayers实战:绘制图形,导出geojson文件
查看>>
Openlayers实战:绘制图形,导出KML文件
查看>>
Openlayers实战:绘制多边形,导出CSV文件
查看>>
Openlayers实战:绘制带箭头的线
查看>>
Openlayers实战:输入WKT数据,输出GML、Polyline、GeoJSON格式数据
查看>>
Openlayers实战:非4326,3857的投影
查看>>
Openlayers高级交互(10/20):绘制矩形,截取对应部分的地图并保存
查看>>
Openlayers高级交互(11/20):显示带箭头的线段轨迹,箭头居中
查看>>
Openlayers高级交互(14/20):汽车移动轨迹动画(开始、暂停、结束)
查看>>