@RequestParam注解在使用过程一些注意。

在项目开发过程的一些教训经验记录。

http接口定义如下:

@RequestMapping(value="/fetchResData",method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
void fetchResData(
  @RequestParam(value = "id")Long id 
 ,@RequestParam(value = "start") String start
 ,@RequestParam(value = "end") String end);

请求方式为POST,Content-Type是json格式,@RequestParam的required属性值默认是true。

客户端在调用该接口,正常传入参数值,但是请求没有进入服务端设置的断点。根据跟踪的异常提示如下:

{
  "timestamp": 1560339674464,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
  "message": "Required Long parameter 'id' is not present",
  "path": "/Service/fetchResData"
}

 进一步分析客户端的请求体信息,如果接口使用@RequestParam绑定基本数据类型情况下,请求的参数是接在URL后面,消息体是没有数据的。而接口定义使用的consumes = MediaType.APPLICATION_JSON_VALUE。因此无法从消息体中获取有效的参数值。从而服务端认为接口参数是必填的,而实际情况是空值。

针对上述问题的解决办法:

1,修改接口定义中consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE 等同于http中content-type为         Content-Type=mutipart/form-data和Content-Type=application/x-www-form-urlencoded

2,Post方式改为Get方式。

 

你可能感兴趣的:(Spring,MVC)