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

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

回答

示例 1:
@RequestParam主要用于过滤目的 假设您想获取 George Martin 的书:
GET localhost:8080/books?author=georgemartin
这里我们author=georgemartin作为请求参数传递。据说这将获得马丁的所有书籍,例如权力的游戏系列。这将主要用于 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


以上是@PathVariable、@RequestParam和@RequestBody之间的区别的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>