簡體   English   中英

什么時候去@RequestParam和@PathVariable

[英]When to go for @RequestParam and @PathVariable

只是想知道在哪種情況下我們應該選擇@RequestParam@PathVariable 我知道:

  1. @RequestParam采用參數值,而@PathVariable采用占位符值
  2. @RequestParam可以是可選的(必需=假),同時使請求而@PathVariable值必須被提供。
  3. 當我們想要使用@RequestParam我們必須知道屬性語法,但不需要@PathVariable

有沒有其他理由去特定的?

如果要遵守“statefull”網址,請使用@PathVariable

例如:-

/customer/:id   Customer view/edit page
/customer/      Customer Add page
/customer/list  List Customer Page
/customer/:cid/order  All order of a Customer
/customer/:cid/order/:oid  Specific order of a partucular Customer.

明智地使用Path Variable將導致URL提供關於結果視圖/頁面的含義的提示/線索。

這也使您無需額外工作即可支持刷新,后退和前進操作。

@RequestParams可用於擴展未作為路徑參數傳遞的數據。 您的MVC處理程序可以根據需要組合使用兩個。

最佳實踐:

  • 如果要標識資源,則應使用“路徑變量”。
  • 但是,如果要對項目進行排序或過濾,則應使用查詢參數。

例:

 /users # Fetch a list of users
/users?occupation=programmer # Fetch a list of user with filter programmer
/users/123 # Fetch a user who has id 123

你可以得到副作用。 您不必定義其他URL和其他查詢參數來實現基本的CRUD功能。您更改HTTP方法取決於您要執行的操作。

/users [GET] # Fetch a list of users
/users [POST] # Create new user
/users/123 [PUT] # Update user
/users/123 [DELETE] # remove user

模板URL中放置可選參數最終會變得非常混亂,所以我建議在Query String中放置可選參數。

暫無
暫無

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

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