文章目錄
- 一、請求路徑參數
- 1、@PathVariable
- 二、Body參數
- 1、@RequestParam
- 2、@RequestBody
- 三、請求頭參數和Cookie參數
- 1、@RequestHeader
- 2、@CookieValue
一、請求路徑參數
1、@PathVariable
注解為:
org.springframework.web.bind.annotation.@PathVariable
獲取路徑參數,即 url/{id}
這種形式,如下請求路徑中 1
即為這里的 {id}
。
http://localhost:8080/param/path/1
對應的 Java
代碼:
@RequestMapping(value = "/param/path/{id}")
public String pathParams(@PathVariable(name = "id") String id){return "return id = " + id;
}
Postman
請求測試結果:
二、Body參數
1、@RequestParam
注解為:
org.springframework.web.bind.annotation.@RequestParam
獲取查詢參數,即 url?id=&name=
這種形式,如下請求(這里以GET請求方式為例)中,1
為 id
值,davis
為 name
值。
http://localhost:8080/param/request?id=1&name=davis
對應的 Java
代碼:
@RequestMapping(value = "/param/request")
public String requestParams(@RequestParam(name = "id", required = false) String id, @RequestParam(name = "name", required = false) String name){return "return id = " + id + ", name = " + name;
}
required = false
表示該參數可以不存在。
注:
-
此方式一個參數對應一個注解,適用于少參數請求。
-
此方式支持GET、POST請求。
Postman
請求測試結果:
GET請求方式
POST請求方式
2、@RequestBody
注解為:
org.springframework.web.bind.annotation.@RequestBody
注:此種方式只支持POST請求。
請求地址:
http://localhost:8080/param/body
對應的 Java
代碼:
@RequestMapping(value = "/param/body", method = RequestMethod.POST)
public String bodyParams(@RequestBody Map<String, Object> maps){return "return " + maps.toString();
}
注:此種方式請求的 Content-Type
必須為 application/json
。
Postman
請求測試結果:
以上使用的是 Map
對象接收的參數,其實我們也可以使用 實體類對象(Person)
來接收參數。
請求地址:
http://localhost:8080/param/body2
對應的 Java
代碼:
@RequestMapping(value = "/param/body2", method = RequestMethod.POST)
public Person bodyParams2(@RequestBody Person person){return person;
}
實體類 Person
,這里使用了 Lombok注解
。
import lombok.Data;@Data
public class Person {private String id;private String name;
}
注:此種方式請求的 Content-Type
必須為 application/json
。
Postman
請求測試結果:
三、請求頭參數和Cookie參數
1、@RequestHeader
注解為:
org.springframework.web.bind.annotation.@RequestHeader
請求地址:
http://localhost:8080/param/header
對應的 Java
代碼:
@RequestMapping(value = "/param/header")
public String headerParams(@RequestHeader(name = "header", required = false) String header){return "return header = " + header;
}
注:此方式支持GET、POST請求。
Postman
請求測試結果:
2、@CookieValue
注解為:
org.springframework.web.bind.annotation.@CookieValue
請求地址:
http://localhost:8080/param/header
對應的 Java
代碼:
@RequestMapping(value = "/param/cookie")
public String cookieParams(@CookieValue(name = "cwcookie", required = false) String cwcookie){return "return cookie = " + cwcookie;
}
注:此方式支持GET、POST請求。
Postman
請求測試結果: