I am trying to create a request log for my web app. I am using Spring 3. 0.
I implemented a class extending HandlerInterceptorAdapter
and used the preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
to intercept the request.
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();
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?
Simple implementation for small requests. Don't use it for multipart request.
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.
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.
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.
Spring has a ready filter to do that for you - see usage of
AbstractRequestLoggingFilter
and its subclasses described in this answer.Be aware that when using this solution, the request body will be logged only after the request processing is complete and the body has been read by your application.