Optimizing web applications with gzip (filter implementation)


Using gzip to optimize web applications (filter implementation) http://john-kong19.iteye.com/blog/1038941
How tomcat uses Gzip to compress static files 2 http://panyongzheng.iteye.com/blog/2249815


How tomcat uses Gzip Compressing static files 1 http://www.wuji8.com/meta/568440954.htmlConfigure


the gzip compression function of Apache and Tomcathttp: //kangyang.blog.51cto.com/471772/580883About
the gzip static compression method of JavaScript http://badqiu.iteye.com/blog/37176


Related knowledge:

  gzip is an encryption algorithm used in the http protocol. After the client sends a request to the web server, the server usually sends the page file and other The resource is returned to the client, and rendered and rendered after the client loads. In this case, the file is generally relatively large. If Gzip is enabled, after the server responds, the page, JS, CSS and other text files or other files are passed through a high compression algorithm. It is compressed and then transmitted to the client, where the client's browser is responsible for decompression and rendering. Usually it can save more than 40% of the traffic (generally about 60%), and some PHP and JSP files can also be compressed.

Implementation:  

Tomcat enables Gzip:

1. Find server.xml under conf in the Tomcat directory, and find the following information
Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true"

Change it to the following form (in fact, there are already under the above code, just open them.):
<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 --> <Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" compression="on" compressionMinSize="2048" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml" >

In this way, html and xml can be compressed. If you want to compress css and js, you need to add

compressableMimeType=”text/html,text/xml” to css and js:

<Connector port="8080" ..... .... compressableMimeType="text/html,text/xml,text/css,text/javascript" >
You can even compress images:

compressableMimeType="text/html,text/xml" add css and js:

<Connector port= "8080" ......... compressableMimeType="text/html,text/xml,text/css,text/javascript,image/gif,image/jpg" >
Restart Tomcat after opening, and view headers through browser The information can see whether it is enabled (in firebug), if it is enabled, then transfer-encoding will be Gzip, otherwise it will be chunked.



Complete the opening of gzip compression for web applications at the code level:
1. Wrapper is used to wrap the HttpServletResponse object
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Wrapper extends HttpServletResponseWrapper
{
    public static final int OT_NONE = 0, OT_WRITER = 1, OT_STREAM = 2;
    private int outputType = OT_NONE;
    private ServletOutputStream output = null;
    private PrintWriter writer = null;
    private ByteArrayOutputStream buffer = null;
    public Wrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        buffer = new ByteArrayOutputStream();
    }
    public PrintWriter getWriter() throws IOException {
        if(outputType==OT_STREAM)
            throw new IllegalStateException();
        else if(outputType==OT_WRITER)
            return writer;
        else {
            outputType = OT_WRITER;
            writer = new PrintWriter(new OutputStreamWriter(buffer, getCharacterEncoding()));
            return writer;
        }
    }
    public ServletOutputStream getOutputStream() throws IOException {
        if(outputType==OT_WRITER)
            throw new IllegalStateException();
        else if(outputType==OT_STREAM)
            return output;
        else {
            outputType = OT_STREAM;
            output = new WrappedOutputStream(buffer);
            return output;
        }
    }
    public void flushBuffer() throws IOException {
        if(outputType==OT_WRITER)
            writer.flush();
        if(outputType==OT_STREAM)
            output.flush();
    }
    public void reset() {
        outputType = OT_NONE;
        buffer.reset();
    }
    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();

    }
    class WrappedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream buffer;
        public WrappedOutputStream(ByteArrayOutputStream buffer) {
            this.buffer = buffer;
        }
        public void write(int b) throws IOException {
            buffer.write(b);
        }
        public byte[] toByteArray() {
            return buffer.toByteArray();
        }
    }
}



package com.shop.gzip;

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 Wrapper extends HttpServletResponseWrapper {
    public static final int OT_NONE = 0, OT_WRITER = 1, OT_STREAM = 2;
    private int outputType = OT_NONE;
    private ServletOutputStream output = null;
    private PrintWriter writer = null;
    private ByteArrayOutputStream buffer = null;

    public Wrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        buffer = new ByteArrayOutputStream();
    }

    public PrintWriter getWriter() throws IOException {
        if (outputType == OT_STREAM)
            throw new IllegalStateException();
        else if (outputType == OT_WRITER)
            return writer;
        else {
            outputType = OT_WRITER;
            writer = new PrintWriter(new OutputStreamWriter(buffer,
                    getCharacterEncoding()));
            return writer;
        }
    }

    public ServletOutputStream getOutputStream() throws IOException {
        if (outputType == OT_WRITER)
            throw new IllegalStateException();
        else if (outputType == OT_STREAM)
            return output;
        else {
            outputType = OT_STREAM;
            output = new WrappedOutputStream(buffer);
            return output;
        }
    }

    public void flushBuffer() throws IOException {
        if (outputType == OT_WRITER)
            writer.flush();
        if (outputType == OT_STREAM)
            output.flush();
    }

    public void reset() {
        outputType = OT_NONE;
        buffer.reset();
    }

    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();

    }

    class WrappedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream buffer;

        public WrappedOutputStream(ByteArrayOutputStream buffer) {
            this.buffer = buffer;
        }

        public void write(int b) throws IOException {
            buffer.write(b);
        }

        public byte[] toByteArray() {
            return buffer.toByteArray();
        }
    }
}







2. Filters
public class GZipFilter implements Filter
{

public void destroy()
{
  // TODO Auto-generated method stub
  
}

public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException
   {
   System.out.println("Enter filter");
   HttpServletResponse resp = (HttpServletResponse)response;
   Wrapper wrapper = new Wrapper(resp);
   chain.doFilter(request, wrapper);
   byte[] gzipData = gzip(wrapper.getResponseData());
   resp.addHeader("Content-Encoding", "gzip");
   resp.setContentLength(gzipData.length);
   ServletOutputStream output = response.getOutputStream();
   output.write(gzipData);
   output.flush();
   }

public void init(FilterConfig arg0) throws ServletException
{
  // TODO Auto-generated method stub
  
}

private byte[] gzip(byte[] data) {
  ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(10240);
  GZIPOutputStream output = null;
  try {
  output = new GZIPOutputStream(byteOutput);
  output.write(data);
  }
  catch (IOException e) {}
  finally {
  try {
  output.close();
  }
  catch (IOException e) {}
  }
  return byteOutput.toByteArray();
  }

}



package com.shop.gzip;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GZipFilter implements Filter {

    public void destroy() {
    }
      /**
       * Determine whether the browser supports GZIP
       * @param request
       * @return
       */
      private static boolean isGZipEncoding(HttpServletRequest request){
        boolean flag=false;
        String encoding=request.getHeader("Accept-Encoding");
        if(encoding.indexOf("gzip")!=-1){
          flag=true;
        }
        return flag;
      }
      
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req=(HttpServletRequest)request;
        if(isGZipEncoding(req)){
            Wrapper wrapper = new Wrapper(resp);
            chain.doFilter(request, wrapper);
            byte[] gzipData = gzip(wrapper.getResponseData());
            resp.addHeader("Content-Encoding", "gzip");
            resp.setContentLength(gzipData.length);
            ServletOutputStream output = response.getOutputStream();
            output.write(gzipData);
            output.flush();
        } else {
            chain.doFilter(request, response);
        }        

    }

    public void init(FilterConfig arg0) throws ServletException {

    }

    private byte[] gzip(byte[] data) {
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(10240);
        GZIPOutputStream output = null;
        try {
            output = new GZIPOutputStream(byteOutput);
            output.write(data);
        } catch (IOException e) {
        } finally {
            try {
                output.close();
            } catch (IOException e) {
            }
        }
        return byteOutput.toByteArray();
    }

}


3. Configure GZipFilter in web.xml. When we access the use of resources ending with .do in the application, http gzip compression is enabled on the server side, and the compressed information is passed to the browser through the http protocol. 
<filter> 

  <filter-name>ecsideExport</filter-name>  

  <filter-class>com.web.servlet.GZipFilter</filter-class>  

</filter>  

<filter-mapping>  

             <filter-name>ecsideExport</filter-name>  

            <url-pattern>*.do</url-pattern>  

</filter-mapping>  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946528&siteId=291194637