I have a servlet that handle certain HTTP requests and responses. I want to log the response body before sending back to the client. Is there any way that I can capture the response body before it is send as a HttpServletResponse object from the servlet?
I have a servlet that handle certain HTTP requests and responses. I want to
Share
If I understand you correctly, you want to log the response body?
As @duffymo pointed out, a
Filteris indeed a suitable place for this. You can capture the response body by replacing the passed-inServletResponsewith aHttpServletResponseWrapperimplementation which basically replaces theHttpServletResponse#getWriter()/getOutputStream()with an own implementation which copies the response body into some buffer. After continuing the filter chain with the replaced response, just capture and log the copy.You can find in this answer a kickoff example how the
doFilter()method can look like.