Created
March 14, 2023 16:40
-
-
Save dimuthnc/8d16785a44471635f4cf7f6f557036b3 to your computer and use it in GitHub Desktop.
A simple Response Wrapper to modify Response using a Servlet Filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.dimuth; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStreamWriter; | |
import java.io.PrintWriter; | |
import javax.servlet.ServletOutputStream; | |
import javax.servlet.http.HttpServletResponse; | |
import javax.servlet.http.HttpServletResponseWrapper; | |
public class ResponseWrapper extends HttpServletResponseWrapper { | |
private final ByteArrayOutputStream capture; | |
private ServletOutputStream output; | |
private PrintWriter writer; | |
public ResponseWrapper(HttpServletResponse response) { | |
super(response); | |
capture = new ByteArrayOutputStream(response.getBufferSize()); | |
} | |
@Override | |
public ServletOutputStream getOutputStream() { | |
if (writer != null) { | |
throw new IllegalStateException("getWriter() has already been called on this response."); | |
} | |
if (output == null) { | |
// inner class - lets the wrapper manipulate the response | |
output = new ServletOutputStream() { | |
@Override | |
public void write(int b) throws IOException { | |
capture.write(b); | |
} | |
@Override | |
public void flush() throws IOException { | |
capture.flush(); | |
} | |
@Override | |
public void close() throws IOException { | |
capture.close(); | |
} | |
}; | |
} | |
return output; | |
} | |
@Override | |
public PrintWriter getWriter() throws IOException { | |
if (output != null) { | |
throw new IllegalStateException("getOutputStream() has already been called on this response."); | |
} | |
if (writer == null) { | |
writer = new PrintWriter(new OutputStreamWriter(capture, getCharacterEncoding())); | |
} | |
return writer; | |
} | |
@Override | |
public void flushBuffer() throws IOException { | |
super.flushBuffer(); | |
if (writer != null) { | |
writer.flush(); | |
} else if (output != null) { | |
output.flush(); | |
} | |
} | |
public byte[] getCaptureAsBytes() throws IOException { | |
if (writer != null) { | |
writer.close(); | |
} else if (output != null) { | |
output.close(); | |
} | |
return capture.toByteArray(); | |
} | |
public String getCaptureAsString() throws IOException { | |
return new String(getCaptureAsBytes(), getCharacterEncoding()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment