今天与同事调试一个接口,发现后台使用@RequestBody老是获取不到数据。查了网上很多资料,要使用@RequestBody来转换JSON字符串为对象,大概是以下几个点:
1. 请求的Content-Type要是application/json
2. 请求的类型要是POST
3. 前台json传递的key在后台的实体对象中存在,也就是JSON要与实体对象要对应,并且名称要一致(如果不一致可以使用@JsonProperty来做映射)
以上这些我基本都检查过了,都没有问题,但是程序根本就不会进入接口方法,详细检查了前端传送到后台确实 application/json类型的数据。如下图:
POST /quickstart/api/v1/dataSync/syncUser HTTP/1.1
Content-Length: 67
Host: 192.168.1.231:9090
Content-Type: application/json
{"username": "1111","password": "e10adc3949ba59abbe56e057f20f883e"}
HTTP/1.1 400 Bad Request
Content-Length: 0
Server: Jetty(7.6.15.v20140411)
SpringMVC也没有抛出任何错误,于是在接口Controller加入以下异常处理代码来确定异常信息:
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public void messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){
//调试作用,用来调试前台传递json后台无法正确映射问题
logger.error("请求参数不匹配。", exception);
}
终于后台打印出错误信息如下:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
at [Source: org.eclipse.jetty.server.HttpInput@42f0d7f3; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164) ~[jackson-databind-2.4.0.jar:2.4.0]
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3095) ~[jackson-databind-2.4.0.jar:2.4.0]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3036) ~[jackson-databind-2.4.0.jar:2.4.0]
但是还是找不到问题所在,最后无意发现前面有一段测试代码(因为程序一直无法进入Controller的接口方法,所以我在Spring拦截器中加了一段代码),测试前端传过来的JSON数据的内容。也就是这段代码导致了这一切。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuffer buffer = new StringBuffer();
String line = " ";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
System.out.println(buffer.toString());
查看文档,发现HttpServletRequest.getInputStream(),一般只能被调用一次,在request.getinputstream读取一次后position到了文件末尾,第二次就读取不到数据,由于无法reset(),所以,request.getinputstream只能读取一次。
做了几年程序第一次知道HttpServletRequest.getInputStream()只能被读取一次,,真是学艺不精啊。