@RequestParam @RequestBody @PathVariable 参数绑定注解详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Andrew_Yuan/article/details/84853005

1、 @PathVariable

当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。

如:

@RequestMapping(value = "/assign/{staffId}/{departmentId}", method = RequestMethod.GET) 
@ApiOperation(value = "人员分配主部门", notes = "人员分配主部门")
  public ResultDto<String> assignPrimaryDepartment(@PathVariable String staffId,@PathVariable String departmentId) {
try { 
   departmentService.assignDepartment(staffId,departmentId);
   return ResultDtoFactory.toAck("success");
} catch (Exception e) {  
   log.error("人员分配主部门" , e);
   return ResultDtoFactory.toNack("人员分配主部门失败");
    }
}

2、@RequestParam, @RequestBody

@RequestParam 

A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

@RequestBody

该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。

因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;

猜你喜欢

转载自blog.csdn.net/Andrew_Yuan/article/details/84853005