[英]When to go for @RequestParam and @PathVariable
只是想知道在哪種情況下我們應該選擇@RequestParam
和@PathVariable
。 我知道:
@RequestParam
采用參數值,而@PathVariable
采用占位符值 @RequestParam
可以是可選的(必需=假),同時使請求而@PathVariable
值必須被提供。 @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處理程序可以根據需要組合使用兩個。
org.springframework.web.bind.annotation.RequestParam
用於綁定查詢字符串 。 org.springframework.web.bind.annotation.PathVariable
用於綁定URL路徑 。 org.springframework.web.bind.annotation.RequestBody
用於綁定HTTP Body 。 org.springframework.http.RequestEntity
將為您提供一些額外的靈活性,可以在HTTP Body中定義任意HTTP 實體標頭 。 例:
/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.