SpringBoot Controller接收引數的幾種常用方式
阿新 • • 發佈:2018-12-12
第一類:請求路徑引數
1、@PathVariable
獲取路徑引數。即url/{id}這種形式。
2、@RequestParam
獲取查詢引數。即url?name=這種形式
例子
GET
http://localhost:8080/demo/123?name=suki_rong
對應的java程式碼:
@GetMapping("/demo/{id}")
public void demo(@PathVariable(name = "id") String id, @RequestParam(name = "name") String name) {
System.out.println("id=" +id);
System.out.println("name="+name);
}
- 1
- 2
- 3
- 4
- 5
輸出結果:
id=123
name=suki_rong
第二類:Body引數
因為是POST請求,這裡用Postman的截圖結合程式碼說明
1、@RequestBody
例子
對應的java程式碼:
@PostMapping(path = "/demo1")
public void demo1(@RequestBody Person person) {
System.out.println(person.toString());
}
- 1
- 2
- 3
- 4
輸出結果:
name:suki_rong;age=18;hobby:programing
也可以是這樣
@PostMapping(path = "/demo1")
public void demo1(@RequestBody Map<String, String> person) {
System.out.println(person.get("name"));
}
- 1
- 2
- 3
- 4
輸出結果:
suki_rong
2、無註解
例子
對應的java程式碼:
@PostMapping(path = "/demo2")
public void demo2(Person person) {
System.out.println(person.toString());
}
- 1
- 2
- 3
- 4
輸出結果:
name:suki_rong;age=18;hobby:programing
Person類
public class Person {
private long id;
private String name;
private int age;
private String hobby;
@Override
public String toString(){
return "name:"+name+";age="+age+";hobby:"+hobby;
}
// getters and setters
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
第三類:請求頭引數以及Cookie
1、@RequestHeader
2、@CookieValue
例子
java程式碼:
@GetMapping("/demo3")
public void demo3(@RequestHeader(name = "myHeader") String myHeader,
@CookieValue(name = "myCookie") String myCookie) {
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
}
- 1
- 2
- 3
- 4
- 5
- 6
也可以這樣
@GetMapping("/demo3")
public void demo3(HttpServletRequest request) {
System.out.println(request.getHeader("myHeader"));
for (Cookie cookie : request.getCookies()) {
if ("myCookie".equals(cookie.getName())) {
System.out.println(cookie.getValue());
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-2787195726.css" rel="stylesheet">
</div>