/ DEVELOPMENT,Java,WEB Java/Web: GZIP compression with Http Filter, GZIPFilter, GZIPResponseStream, GZIPResponseWrapper

Java/Web: GZIP compression with Http Filter, GZIPFilter, GZIPResponseStream, GZIPResponseWrapper


The bandwidth is an important concern of the production management of a website. A recognized method of all browsers and systems to drastically reduce the bandwidth usage is the Zip compression of data sent on the fly, decompressed without loss and displayed by the browser. In this article, we will discuss about the configuration of gzip compression in the client-server exchanges of Web based application. The protocol used is called GZIP.

Side browsers, most (99%) browsers can decode gzipped content. The header of such content is ‘Content-Encoding: gzip’, and is accepted by all browsers support HTTP 1.1, so ‘Content-Encoding’. Side of the web servers, the existence or installation of gzip module on a webserver does not necessarily lead to data compression, because it compresses the data only if the request from the browser contains the header ‘Accept-Encoding: gzip, deflate’.

Configuration Http filter and classes
The web deployment descriptor web.xml must contains the configuration of http filter GZIPFilter:


When a request arrived from browser, on server side, the http filter GZIPFilter will check the need of GZIP compression in request’s headers ‘Accept-Encoding: gzip’. Then, this filter uses two classes GZIPResponseWrapper and GZIPResponseStream to compress the data in response:


package com.ho.filter;

import javax.servlet.*;
import javax.servlet.http.*;

public class GZIPFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
		throws IOException, ServletException {
		if (req instanceof HttpServletRequest) {
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;
			String ae = request.getHeader("accept-encoding");
			if (ae != null && ae.indexOf("gzip") != -1) {
				GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
				chain.doFilter(req, wrappedResponse);
			chain.doFilter(req, res);

	public void init(FilterConfig filterConfig) {
		// noop

	public void destroy() {
		// noop


public class GZIPResponseWrapper extends HttpServletResponseWrapper {
  protected HttpServletResponse origResponse = null;
  protected ServletOutputStream stream = null;
  protected PrintWriter writer = null;

  public GZIPResponseWrapper(HttpServletResponse response) {
    origResponse = response;

  public ServletOutputStream createOutputStream() throws IOException {
    return (new GZIPResponseStream(origResponse));

  public void finishResponse() {
    try {
      if (writer != null) {
      } else {
        if (stream != null) {
    } catch (IOException e) {}

  public void flushBuffer() throws IOException {

  public ServletOutputStream getOutputStream() throws IOException {
    if (writer != null) {
      throw new IllegalStateException("getWriter() has already been called!");

    if (stream == null)
      stream = createOutputStream();
    return (stream);

  public PrintWriter getWriter() throws IOException {
    if (writer != null) {
      return (writer);

    if (stream != null) {
      throw new IllegalStateException("getOutputStream() has already been called!");

   stream = createOutputStream();
   writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
   return (writer);

  public void setContentLength(int length) {}


public class GZIPResponseStream extends ServletOutputStream {
  protected ByteArrayOutputStream baos = null;
  protected GZIPOutputStream gzipstream = null;
  protected boolean closed = false;
  protected HttpServletResponse response = null;
  protected ServletOutputStream output = null;

  public GZIPResponseStream(HttpServletResponse response) throws IOException {
    closed = false;
    this.response = response;
    this.output = response.getOutputStream();
    baos = new ByteArrayOutputStream();
    gzipstream = new GZIPOutputStream(baos);

  public void close() throws IOException {
    if (closed) {
      throw new IOException("This output stream has already been closed");

    byte[] bytes = baos.toByteArray();

    response.addHeader("Content-Encoding", "gzip");
    closed = true;

  public void flush() throws IOException {
    if (closed) {
      throw new IOException("Cannot flush a closed output stream");

  public void write(int b) throws IOException {
    if (closed) {
      throw new IOException("Cannot write to a closed output stream");

  public void write(byte b[]) throws IOException {
    write(b, 0, b.length);

  public void write(byte b[], int off, int len) throws IOException {
    if (closed) {
      throw new IOException("Cannot write to a closed output stream");
    gzipstream.write(b, off, len);

  public boolean closed() {
    return (this.closed);
  public void reset() {

These classes are present in the attachment or on the site.

To verify the compression, we could the TCP/IP Monitor view of Eclipse. So, a proxy will be configured in order to analyze the request coming to the server localhost on port 9999, then forward these requests to this same server localhost on port 8080.

…without GZIP configuration:
– the size of response is 27560 bytes,
– the Content-Type of response is text/html; ,
– the header Content-Encoding is missing in response,

…with GZIP configuration:
– the size of response is 2544 bytes,
– the Content-Type of response is text/html; ,
– the header Content-Encoding contains the value gzip in response,

That’s all!!!


Best regards,


8 thoughts on “Java/Web: GZIP compression with Http Filter, GZIPFilter, GZIPResponseStream, GZIPResponseWrapper”

    1. Indeed, you must call the gzipstream.close() method in GZIPResponseStream.close() method if the application has only a single HTTP filter. However, if the application has several HTTP filters, do not call the gzipstream.close() method …

      Note: the javadoc for this GZIPOutputStream.finish() method is:
      Finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

  1. How to handle exceptions in filters , incase filter did not receive proper gzip data . ? Please let me know if any other information needed.

  2. All this much code..geez…If you’re using Tomcat, why not simply use compression=”on” attribute by specifying compressableMimetypes along with compressionMinSize. Why write so much code when you’ve built-in capabilities to compress response????

    1. You are right, but by this coding solution, we have the possibility to compress sensible/confidential data, not all data returned by the server.

  3. I’m having a problem with ehcache gzipfilter, the response is not streamed if gzip is enabled. It seems that gzipfilter buffers all documents and then compress and send. Is there a way to configure it to compress and continue streaming?

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post