Search code examples
javaservlets

Capture and log the response body


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?


Solution

  • If I understand you correctly, you want to log the response body?

    As @duffymo pointed out, a Filter is indeed a suitable place for this. You can capture the response body by replacing the passed-in ServletResponse with a HttpServletResponseWrapper implementation which basically replaces the HttpServletResponse#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.