Springboot中@PathVariable,@RequestParam,@RequestBody,HttpServletRequest区别

@PathVariable

//接收请求URL中占位符的值
@GetMapping("/getId/{id}")//{id}写在请求URL中,参数来源于URL中,所以@PathVariable可以多个
//单个入参时id可不写,多个入参需要写
public String pathVariable(@PathVariable("id") Integer id) {

}

@RequestParam

//将URL的请求参数绑定到控制器的方法参数上
@GetMapping("/getId")//例:getId?id=0001,参数来源于URL中,所以@RequestParam可以多个
//单个入参时id可不写,甚至@RequestParam("id")都可不写,多个入参需要写全
public String requestParam(@RequestParam("id") Integer id) {

}

@RequestBody

//接收的是请求体里面的数据
@PostMapping("/getRequestBody")
//入参可以为:实体类,Map ,JsonObject,String等可存储key-value的对象
//参数来源于请求body中,所以@RequestBody只能一个
public String RequestBody(@RequestBody User user) {

}

HttpServletRequest

//通过getParameter直接获取,参数来源于URL中
@GetMapping("/getHttpServletRequest")
public String getHttpServletRequestValue(HttpServletRequest request) {
  String id = request.getParameter("id");
}

//通过参数集获取,参数来源于URL中
@GetMapping("/getHttpServletRequest")
public String getHttpServletRequestValue(HttpServletRequest request) {
  Map<String, String[]> parameterMap = request.getParameterMap();
  String[] ids = parameterMap.get("id");
  String id = ids[0];
}

//通过流获取body中的值,参数来源于请求body中
@PostMapping("/getHttpServletRequest")
public String getHttpServletRequestValue(HttpServletRequest request) throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
  String line = "";
  String body = "";
  while((line = reader.readLine()) != null){
    body += line;
  }
  JSONObject jsonObject=JSONObject.parseObject(body);
  Integer id =  jsonObject.getInteger("id");
}
发布了43 篇原创文章 · 获赞 12 · 访问量 9862

猜你喜欢

转载自blog.csdn.net/OrangeHap/article/details/103563155