If I understand you correctly, do you want to register the response body ? This is quite an expensive task, but if it is a business requirement ...
As shown in the figure, a Filter is the right place for this. You can capture the response body by replacing the passed ServletResponse with HttpServletResponseWrapper , which replaces HttpServletResponse#getWriter() its own implementation, which copies the response body to some buffer. After continuing the filter circuit with the replaced answer, just write a copy.
Here's an example of how the doFilter() method looks like:
public void doFilter(ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException { final CopyPrintWriter writer = new CopyPrintWriter(response.getWriter()); chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) { @Override public PrintWriter getWriter() { return writer; } }); logger.log(writer.getCopy()); }
Here's what CopyPrintWriter looks CopyPrintWriter :
public class CopyPrintWriter extends PrintWriter { private StringBuilder copy = new StringBuilder(); public CopyPrintWriter(Writer writer) { super(writer); } @Override public void write(int c) { copy.append((char) c);
Match this filter to the url-pattern for which you want to register responses. Keep in mind that binary / static content, such as images, CSS, JS files, etc., will not be logged this way. You want to exclude them using a fairly specific url-pattern value, for example. *.jsp or only on the servlet-name the servlet in question. If you want to write binary / static content anyway (for which I see no use), you need to replace HttpServletResponse#getOutputStream() .
BalusC Jul 14 2018-10-10T00: 00-07
source share