javascript
Spring @RequestParam批注
介紹:
Spring @RequestParam批注可用于在處理程序方法中提取查詢參數。 在本快速教程中,我們將學習其用法。
首先讓我們展示一個API,該API返回具有給定名字和年齡的用戶列表:
@RestController public class UserController {...@GetMapping("/users")public List<User> getUsers(@RequestParam String firstName, @RequestParam int age) {return userService.findUsersWith(firstName, age);} }現在,讓我們使用cURL快速測試一下:
curl -XGET 'http://localhost:8080/users?firstName=John&age=15' ... [{firstName = John ,lastName = Mason ,age = 15}, {firstName = John ,lastName = Dash ,age = 15}]如我們所見, firstName和age是正確映射到我們的處理程序方法的查詢參數。
@RequestParam批注支持使用多種屬性來滿足各種常見需求:
1.
在剛剛介紹的示例中,我們將注意到方法參數和查詢參數的名稱相同( firstName和age )。
但是, 有時,我們可能會覺得需要使用不同的名稱。 為此,我們將使用其name或value屬性 :
@GetMapping("/users") public List<User> getUsers(@RequestParam(name="uName") String firstName, @RequestParam("uAge") int age) {return userService.findUsersWith(firstName, age); }這樣,UNAME和uAge參數將分別映射到firstName和年齡的方法參數:
curl -XGET 'http://localhost:8080/users?uName=John&uAge=15'2.
默認情況下, 如果我們定義了一個請求參數,并且未在用戶請求中傳遞它,則會收到錯誤消息。
為了避免這種情況,我們可以將required設置為false:
@GetMapping("/users") public List<User> getUsers(@RequestParam(required=false) String firstName, @RequestParam int age) {return userService.findUsersWith(firstName, age); }它將為所有可選參數分配默認數據類型。 當我們點擊以下URL時:
http://localhost:8080/users?age=15firstName將被映射為空值。
3.
如果我們想要將required設置為false并且還將默認值映射到所關注的屬性,我們將具有:
@GetMapping("/users") public List<User> getUsers(@RequestParam(defaultValue="John") String firstName,@RequestParam int age) { return userService.findUsersWith(firstName, age); }在這里,如果我們不傳遞firstName查詢參數,它將假定它是'John' 。
我們可以在Java 列表中接受查詢參數的列表:
@GetMapping("/users/v2") public List<User> getUsersWithGivenAges(@RequestParam List<Integer> age) {return userService.findUsersWithAges(age); }要使用我們的新用戶API,我們將提供以下內容:
curl -XGET 'http://localhost:8080/users/v2?age=10,15,20'Orcurl -XGET 'http://localhost:8080/users/v2?age=10&age=15&age=20'檢索所有參數:
要從用戶請求中檢索所有傳遞的查詢參數,我們將其接受為Java Map :
@GetMapping("/paramsEx") public Map<String, String> printParams(@RequestParam Map<String, String> allQueryParams) {System.out.println(allQueryParams); return allQueryParams; }當我們想檢索所有參數而不知道它們的名稱時,這很方便:
curl -XGET 'http://localhost:8080/paramsEx?param1=A¶m2=B¶m3=2' ... {param1=A, param2=B, param3=2}結論:
在本教程中,我們學習了如何在Spring應用程序中使用@RequestParam批注。
翻譯自: https://www.javacodegeeks.com/2019/10/spring-requestparam-annotation.html
總結
以上是生活随笔為你收集整理的Spring @RequestParam批注的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux与macos(linux与ma
- 下一篇: 电鼓垫app(电鼓垫安卓)