簡體   English   中英

@PathVariable、@RequestParam 和 @RequestBody 之間的區別

[英]Difference between @PathVariable, @RequestParam, and @RequestBody

我了解@PathVariable@RequestParam@RequestBody在 Spring 中的作用,但不清楚我們必須在哪些場景中使用它們,因為它們用於從 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.ZFC35FDC70D5FC69D26EZ83A83A8
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.ZFC35FDC70D5FC69D226EZ83A8
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PathVariable.ZFC35FDC70D52FC69D269E883A8A8

@PathVariable用於部分路徑(即/person/{id})

@RequestParam用於 GET 查詢參數(即 /person?name="Bob")。

@RequestBody用於請求的實際正文。

@RequestBody 與 POST 動詞一起使用,而 @RequestParam 和 @pathVariable 與 GET 動詞一起使用

@RequstParam:它從用於過濾、排序和分頁的查詢字符串中提取值在請求參數中,值可以加密 localhost:8080/getBooks?start=1&end=100

@pathVariable:它從URI路徑中提取值在路徑變量中,值不能被編碼它用於根據值獲取數據

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM