记录HttpRequest参数和请求正文 [英] Logging HttpRequest parameters and request body
问题描述
我正在尝试为我的Web应用程序创建请求日志.我正在使用Spring 3. 0.
I am trying to create a request log for my web app. I am using Spring 3. 0.
我实现了扩展HandlerInterceptorAdapter
的类,并使用preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
拦截了请求.
I implemented a class extending HandlerInterceptorAdapter
and used the preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
to intercept the request.
在该方法中,我希望能够记录请求正文(我的参数是直接写入请求正文的XML对象),为此,我使用request.getReader();
In the method i want to be able to log the request body (my parameters are objects in XML that are written directly to the request body), and for that i use request.getReader();
问题是-稍后,当spring控制器尝试读取请求时,我会得到一个IllegalStateException
.
The problem is - later on I will get an IllegalStateException
when the spring controller tries to read the request.
有没有办法做我打算做的事?
Is there a way to do what I intend?
推荐答案
您可以使用过滤器执行此操作.请求参数易于处理. 但是,处理请求主体将更加困难 并且需要包装servlet请求,请参见: HttpServletRequest .
You can do this with a filter. The request parameters are easy to handle. However dealing with the request body will be much more difficult and will require wrapping the servlet request see: HttpServletRequest.
您将需要查看传入的请求的大小,并确定是将请求正文存储为tmp文件还是字符串.
You will need to look how big the incoming request is and decide whether you want to store the request body as a tmp file or string.
您将需要使用用于记录日志的文件或保存的字符串覆盖ServetRequest.getInputStream().
You will need to override ServetRequest.getInputStream() with your file or saved string that used for logging.
如果请求主体很大,我建议将输入流放入缓冲的输入流中,然后读取主体的开头.
If the request body is huge I recommend putting the input stream into a buffered input stream and then reading the start of the body.
public class LogRequest extends HttpServletRequestWrapper {
public LogRequest(HttpServletRequest request) {
super(request);
}
@Override
public ServletInputStream getInputStream() throws IOException {
//read from tmp file or string.
}
@Override
public BufferedReader getReader() throws IOException {
//read from tmp file or string
}
}
这篇关于记录HttpRequest参数和请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!