2014-06-22 71 views
1

我正在开发Spring MVC应用程序。我写了一个mvc:拦截器来打印传入请求的JSON内容。我尝试了两种方式来做到这一点,但都不起作用。打印HttpServletRequest JSON内容

第一种使用getReader()的方法不起作用,因为getReader()只能调用一次,看起来它已被容器调用,所以建议使用ServletInputStream接口。我有以下代码:

public class RequestInterceptor implements HandlerInterceptor { 

private static final Logger logger = LoggerFactory.getLogger(RequestInterceptor.class); 


@Override 
public boolean preHandle(HttpServletRequest request, 
     HttpServletResponse response, Object handler) throws Exception { 

    logger.info("Received HTTP request with URL:" + request.getRequestURL()); 

    ServletInputStream in = request.getInputStream(); 
    byte[] buf = new byte[1000]; 
    StringBuilder sb = new StringBuilder(); 
    for (int nChunk = in.read(buf); nChunk!=-1; nChunk = in.read(buf)) 
    { 
     sb.append(new String (buf, 0, nChunk)); 
    } 

    logger.info("Request JSON Content" + sb.toString()); 


    return true; 
} 
... 
} 

这种方法的问题是,它通过拦截,并获得了春天控制器后,它变得没有输入,可能是因为我已经函数读取输入。

我得到以下日志消息:

INFO : com.feelstream.server.interceptors.RequestInterceptor - Received HTTP request with URL:http://localhost:8090/server/FsServer/push_event 
INFO : com.feelstream.server.interceptors.RequestInterceptor - Request JSON Content{ 
    "evt_time":7, 
    "cell_id":7866, 
    "cell_lac":31, 
    "device_id":"62c7c7042511c086", 
    ... 
} 



DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Reading [class com.feelstream.utils.Event] as "application/json" using [org.springfr[email protected]4bec03a6] 
DEBUG: org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public com.feelstream.utils.Response com.feelstream.server.controller.FsController.pushEvent(com.feelstream.utils.Event,org.springframework.validation.BindingResult)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: No content to map due to end-of-input 
at [Source: [email protected]; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input 
at [Source: [email protected]; line: 1, column: 1] 
+0

异常提示,输入是不是一个有效的JSON ..你可以请验证在线工具中的JSON一次吗? –

+0

当我删除拦截器时,JSON完美工作。我读了“由于输入结束而没有内容映射”作为空输入,可能是由于第一次阅读。 –

+1

这是日志请求主体的经典问题......它可能是任意长度的链。要么你需要包装请求以允许双重读取,或者如果你打包MappingJackson2HttpMessageConverter会更简单。 –

回答

6

以撒,

您应该能够像任何其他筛选

 <filter> 
     <filter-name>commonsRequestLoggingFilter</filter-name> 
     <filter-class>org.springframework.web.filter.CommonsRequestLoggingFilter</filter-class> 
    <init-param> 
     <param-name>includePayload</param-name> 
     <param-value>true</param-value> 
     </init-param> 
     </filter> 

添加此过滤器在web.xml

这将在Spring读取消息之前记录消息。如果您需要额外的日志记录,则可以扩展此过滤器并添加更多功能。

+0

Thx,这很好。 –