@PathVariable、@RequestParam和@RequestBody之间的区别

5

我理解 Spring 框架中的 @PathVariable@RequestParam@RequestBody 的作用,但不清楚在哪种场景下需要使用它们,因为它们都用于从 URI 提取值。为什么我们要像这样发送数据:localhost:8080/getBooks/time 和 localhost:8080/getBooks?book=time。


4
不要在终端点使用动词,你的情况中使用了getBook/,更好的选择是使用books/,这样符合REST最佳实践。参考:https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/#h-use-nouns-instead-of-verbs-in-endpoint-paths - Ganesh Jadhav
3个回答

15

示例 1:
@RequestParam 主要用于过滤目的 假设您想获取George Martin的书:
GET localhost:8080/books?author=georgemartin
这里我们将 author=georgemartin 作为请求参数传递。这将会获取Martin的所有书籍,例如《权游》系列。 这主要用于 GET 操作。

示例 2:
@PathVariable 主要用于获取单个对象或数据片段 假设您想通过ID获取一本书:
GET localhost:8080/books/1
这里我们将 1 作为路径变量传递。这将会获取 ID 为 1 的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”)中使用动词约定。但是,重要的是要在所有端点上遵循一致的约定。 - Ganesh Jadhav

11

@PathVariable 用于路径的一部分(例如:/person/{id})。

@RequestParam 用于获取 GET 请求中的查询参数(例如:/person?name="Bob")。

@RequestBody 用于请求的实际主体部分。


1

@RequestBody 在POST请求中使用,而@RequestParam和@PathVariable在GET请求中使用

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

@PathVariable:从URI路径中提取值,在路径变量中,值无法被编码。它用于根据值获取数据。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接