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

你可能感兴趣的文章
php flush()刷新不能输出缓冲的原因分析
查看>>
Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig
查看>>
Refactoring-Imporving the Design of Exsiting Code — 代码的坏味道
查看>>
PHP imap 远程命令执行漏洞复现(CVE-2018-19518)
查看>>
php include和require
查看>>
ref 和out 区别
查看>>
php JS 导出表格特殊处理
查看>>
php json dom解析
查看>>
ReentrantReadWriteLock读写锁解析
查看>>
php laravel实现依赖注入原理(反射机制)
查看>>
php laravel请求处理管道(装饰者模式)
查看>>
ReentrantReadWriteLock读写锁底层实现、StampLock详解
查看>>
PHP mongoDB 操作
查看>>
ReentrantLock读写锁
查看>>
ReentrantLock的公平锁与非公平锁
查看>>
php mysql procedure获取多个结果集
查看>>
php mysql query 行数,PHP和MySQL:返回的行数
查看>>
php mysql session_php使用MySQL保存session会话
查看>>
PHP mysql_real_escape_string() 函数防SQL注入
查看>>
php mysql优化方法_MySQL优化常用方法
查看>>