There is some extra understanding needed for this topic.
When the original response is passed by the filter to the servlet, the servlet would write to the servlet's output stream. The moment the service() method completes, the container would flush the stream. (The container would call out.flush()). This would send the response to the client. This flushing always happens after the servlet's service() method is done. The container will not wait for any filter. Now, when the control goes back to the filter, the filter WILL have a reference to the actual response (It was having it even before). But if it tries to call any method on the response, an
IllegalStateException will be thrown as output stream has already been flushed by the container. This explains why you need to send a custom response.
Coming to you second question - why you need a custom response stream. If you prepare a custom response (by extending ServletResponseWrapper) and pass it to the servlet, without overriding the getOutputStream method to return a custom output stream, when the servlet calls getOutputStream on the custom response object, the custom response object would just delegate the call to the original response object that it wraps (which is how ServletResposeWrapper behaves). So think what will happen - the servlet would actually get the original response stream from the custom response object and write to the original response stream. So you have the same problem again, the container would just flush the stream and the response would be sent to the client. So you would need to override the getOutputStream method and return a custom compression response stream from that. When the servlet calls getOutputStream, it would now get the custom compression respnnse stream and write to it. After the servlet writes to it ,you (not the container) would flush it (from the filter by calling finish). This would send the compressed response to the actual response stream (which the custom response stream wraps), which the container would flush and send to the client