How to avoid response being commited in filter
Recently dealing with a problem that the ServletResponse being comminted in Filter class after chain.doFilter() being called. Once ServletResponse is being commited, it won't allow us to manipulate the response any more. After resolved this issue, thought that worth to publish this online to share with every body.
YourFilter - your filter class.
YourController - your controller class that chain.doFilter() goes to
YourMockServletResponse - your mockup ServletResponse class which will act like ServletResponse.
YourResponseWrapper - your response wrapper
YourFilter implements Filter
public void doFilter(request, response, chain)
YourMockServleResponse mockRes = new YourMockServletResponse();
YourResponseWrapper buffer = new YourResponseWrapper ();
//Now you are passing in your mock up response object,
//so the actual response is intact.
String yourData1 = buffer.toString();
//you can actually make multiple calls on chain.doFilter()
//by resetting request attribute.
String yourData2 = buffer.toString();
String yourData = maniputateYourData(data1, data2);
//Manipulate yourData1 and yourData2 to deal with your business
//After you done, output your data
//Now we are using the actual response
PrintWriter writer = response.getWriter();
Here is the rest of the class example.
public class YourResponseWrapper extends HttpServletResponseWrapper
private CharArrayWriter output;
public String toString()
public StringResponseWrapper(HttpServletResponse response)
output = new CharArrayWriter();
public PrintWriter getWriter()
return new PrintWriter(output);
public class MockServletResponse implements HttpServletResponse
private ByteArrayOutputStream outputStream = null;
private PrintWriter out = null;
public ByteArrayOutputStream getOutputStreamNotServlet() throws IOException
if (this.out != null) this.out.flush();
if (this.outputStream != null) this.outputStream.flush();
* Used to close the outout streams if you have used the getWriter(), if not
* the output streams will not be created.
public void closeOutputStream() throws IOException
if (this.out != null) this.out.close();
if (this.outputStream != null) this.outputStream.close();
public PrintWriter getWriter() throws IOException
if (this.outputStream == null)
this.outputStream = new ByteArrayOutputStream();
this.out = new PrintWriter(outputStream);
//You need to implement the rest abstract methods inherited from parent.