注解 | 支持类型 | 支持请求类型 | 支持的Content-Type | 请求示例 |
---|---|---|---|---|
@PathVariable | url | Get | all | /orders/{id} |
@RequestParam | url | Get | all | /orders?id=abc |
- | Body | Post/Put/Delete/Patch | form-data,x-www.form-urlencoded | |
@RequestBody | Body | Post/Put/Delete/Patch | json | {“name”:"Zhang ",“age”:18} |
对于一些非必填参数,可以使用required 关键字来标识,同时必须设置默认值defaultValue
如getOrder方法中对price 参数的获取:
/**
* Get请求的参数可以通过@PathVariable和@RequestParam获取
* @param id 必填
* @param name 必填
* @param price 选填,默认值为0
* @return
*/
@GetMapping("/orders/{id}")
public String getOrder(@PathVariable(value = "id")Integer id,
@RequestParam(value = "name")String name,
@RequestParam(value = "price",required = false,defaultValue = "0") Integer price)
{
String result = "id:"+id+",name:"+name+",price:"+price;
return result;
}
参数可以不配注解直接和Entity类绑定,但是不支持json格式,仅支持form-data和x-www.form-urlencoded格式
@PostMapping("/order/")
public String addorder(Order order)
仅支持Get请求
获取请求路径。例如:url/{id} 形式。
获取查询参数。例如:url?id=123&name=zhangsan 形式。
范例:
GET请求
http://localhost:8080/demo/123?name=zhangsan
服务端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);
}
//PathVariable匹配路径参数,RequestParam匹配?后参数
支持Post/Put/Delete/Patch请求
前端请求:
#post请求
#参数:
{
"name":"zhangsan",
"age":18
}
#参数类型:
`Content-Type=application/json`
#api:
http://localhost:8080/demo1
后台接收:
@PostMapping("/demo1")
public void demo1(@RequestBody User user) {
// 输出:User{name='zhangsan', age=18}
System.out.println(user.toString());
}
// 或者使用map接收
@PostMapping("/demo1")
public void demo1(@RequestBody Map<String, String>user) {
// 输出:zhangsan
System.out.println(user.get("name"));
}
前端请求:
#post请求
#参数:
{
"name":"zhangsan",
"age":18
}
#参数类型:
`Content-Type=form-data`
#api:
http://localhost:8080/demo2
后台接收:
@PostMapping("/demo2")
public void demo2(User user) {
// User{name='zhangsan', age=18}
System.out.println(user.toString());
}
multipart/form-data
与x-www-fom-urlencoded
的区别:
范例:
@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);}
或
@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()); } }}