P
P
parkito2017-03-28 21:29:49
Java
parkito, 2017-03-28 21:29:49

How to write a filter to read body in response?

Hello. Help, please, to solve a problem.
I am writing a filter from which I could extract information from the outputStream

class MyHttpServletResponseWrapper 
  extends HttpServletResponseWrapper {

  private StringWriter sw = new StringWriter(BUFFER_SIZE);

  public MyHttpServletResponseWrapper(HttpServletResponse response) {
    super(response);
  }

  public PrintWriter getWriter() throws IOException {
    return new PrintWriter(sw);
  }

  public ServletOutputStream getOutputStream() throws IOException {
    throw new UnsupportedOperationException();
  }

  public String toString() {
    return sw.toString();
  }
}

However, after I push it into the chain, I get a response body, but the chain breaks there.
HttpServletResponse httpResponse = (HttpServletResponse) response;
MyHttpServletResponseWrapper wrapper = 
  new MyHttpServletResponseWrapper(httpResponse);

chain.doFilter(request, wrapper);

String content = wrapper.toString();

THOSE. I get the page code from the stream, but the page itself is not displayed in the browser.
How can I make it so that when the body is fetched, the page continues to display normally?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Myvrenik, 2017-03-28
@gim0

The fact is that a stream can be read only once, that's why it's a stream. After reading the stream, you need to create a new stream from the same data, swap and feed it further down the chain.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question