【问题标题】:Difference between @PathVariable, @RequestParam, and @RequestBody@PathVariable、@RequestParam 和 @RequestBody 之间的区别
【发布时间】:2021-05-22 12:28:22
【问题描述】:

我了解 @PathVariable、@RequestParam 和 @RequestBody 在 Spring 中的作用,但不清楚我们必须在哪些场景中使用它们,因为它们用于从 URI 中提取值。为什么我们必须发送像 localhost:8080/getBooks/time 和 localhost:8080/getBooks?book=time 这样的数据。

【问题讨论】:

  • 永远不要使用动词作为端点,在您使用 getBook/ 的情况下,最好使用 books/。(遵循 REST 最佳实践)。参考:stackoverflow.blog/2020/03/02/…

标签: java spring spring-boot rest


【解决方案1】:

示例 1:
@RequestParam 主要用于过滤目的 假设您想获得乔治·马丁的书:
GET localhost:8080/books?author=georgemartin
这里我们传递author=georgemartin 作为请求参数。这应该会得到马丁的所有书籍,例如权力的游戏系列。 这将主要用于 GET 操作。

示例2:
@PathVariable主要用于获取单个对象或数据片段 假设您想通过 id 获得一本书:
GET localhost:8080/books/1
这里我们传递 1 作为路径变量。这应该会得到 1 本书,id 为 1,例如权力的游戏书的第一部分。 这将主要用于 DELETE/GET 操作。

示例 3:
@RequestBody 主要用于保存对象(或数据) 假设您想添加一本书:
POST localhost:8080/books/ 请求正文具有以下属性:

{
  "author":"George Martin",
  "Book":"Game of thrones"
  ...
  ...
}

这会将一本书添加到数据库中。这将主要用于 PUT/POST 操作。


注意:不要使用动词命名端点,而是使用复数名词。因此,books/ 是理想的,而不是 getbooks/。
参考/阅读更多:
https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/#h-use-nouns-instead-of-verbs-in-endpoint-paths
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PathVariable.html

【讨论】:

  • 编辑:我们可以对/search 等端点使用动词约定。但我们的想法是遵循一个惯例
【解决方案2】:

@PathVariable 用于部分路径(即 /person/{id})

@RequestParam 用于 GET 查询参数(即 /person?name="Bob")。

@RequestBody 用于请求的实际正文。

【讨论】:

    【解决方案3】:

    @RequestBody 与 POST 动词一起使用,而 @RequestParam 和 @pathVariable 与 GET 动词一起使用

    @RequstParam :从查询字符串中提取值 用于过滤、排序和分页 在请求参数中,值可以被加密 localhost:8080/getBooks?start=1&end=100

    @pathVariable : 从 URI 路径中提取值 在 Path 变量中,无法对值进行编码 它用于根据值获取数据

    参考: https://www.baeldung.com/spring-requestparam-vs-pathvariable

    【讨论】:

      猜你喜欢
      • 2015-03-18
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 2020-01-14
      • 2015-06-04
      相关资源
      最近更新 更多