Skip to content

Instantly share code, notes, and snippets.

@hendrixjoseph
Last active May 25, 2022 17:02
Show Gist options
  • Save hendrixjoseph/fda450a5bd00c1004241bf268a9bf20c to your computer and use it in GitHub Desktop.
Save hendrixjoseph/fda450a5bd00c1004241bf268a9bf20c to your computer and use it in GitHub Desktop.
Lazily Check the Body of an HttpServletResponse
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class LazyResponseBodyChecker extends HttpServletResponseWrapper {
public LazyResponseBodyChecker(final HttpServletResponse response) {
super(response);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
final ServletOutputStream superStream = super.getOutputStream();
return new ServletOutputStream() {
@Override
public void write(final byte buf[]) throws IOException {
// All other methods eventually call this one, so
// just examine the buffer here.
final String string = new String(buf);
final byte newBuf[] = string.getBytes();
write(newBuf, 0, newBuf.length);
}
@Override
public boolean isReady() {
return superStream.isReady();
}
@Override
public void setWriteListener(final WriteListener listener) {
superStream.setWriteListener(listener);
}
@Override
public void write(final int b) throws IOException {
superStream.write(b);
}
};
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(super.getWriter()) {
@Override
public void write(final char[] buf, final int off, final int len) {
final String string = new String(buf);
// examine or modify the string here
super.write(string.toCharArray(), off, len);
}
};
}
}
@hendrixjoseph
Copy link
Author

I used this code in my blog post Lazily Check the Body of an HttpServletResponse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment