Better than a bad memory. 33-Compress response body content with Java filters

Source: Internet
Author: User

In the previous response related content, mentioned the data compression and then uploaded to the browser, through compression, can improve the transmission efficiency of network files, in many places need to be practical.
If we need to implement compression on all pages, does this add to one place and solve it together? It seems that we can load a lot of content in the filter, so is it possible to add this to the filter as well? The answer is yes.
We can compress the response body content by enhancing the Httpservletresponsewrapper object.
1. Principle
Passes a filter filter to the target page to pass a custom response object. In the custom response object, override the Getoutputstream method and the Getwriter method so that when the target resource calls this method, the output page content is obtained from our custom Servletoutputstream object. In our custom Servletouputstream object, rewrite the Write method so that the written data is written out into a buffer. When the page completes the output, the page writes out the data in the filter, so we can call Gzipouputstream to compress the data and then write to the browser, in order to complete the response to the file compression function. You can set the location response header for request redirection (you can view httpservletrequest related content), or you can set the content-encoding response header to tell the browser the compression format of the data, or you can set the Content-type response header , specify the loopback data type, or you can set the Content-disposition response header to allow the browser to download the file (you can view httpservletreonse related content)
You can also use it to do a lot of things.
2. Implement the source code of the compressed response body with Java filter
In the bandwidth is not enough, compression is a good way to solve things, the current bandwidth is getting bigger, but the file is getting bigger, compression or there is a hero. Baidu and other Web sites are also using compressed data transfer methods.

 PackageCom.filter;ImportJava.io.ByteArrayOutputStream;ImportJava.io.IOException;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.util.zip.GZIPOutputStream;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;ImportJavax.servlet.ServletException;ImportJavax.servlet.ServletOutputStream;ImportJavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJavax.servlet.http.HttpServletResponseWrapper;/** * A simple response body compression, filter implementation * @author Fan Fangming */ Public  class easyresponsegzipfilter implements Filter{    @Override     Public void Init(Filterconfig filterconfig)throwsservletexception {System.out.println ("----Filter initialization----"); }@Override     Public void DoFilter(ServletRequest req, Servletresponse resp, filterchain chain)throwsIOException, servletexception {httpservletrequest request = (httpservletrequest) req;        HttpServletResponse response = (httpservletresponse) resp; BufferResponse Myresponse =NewBufferResponse (response); Chain.dofilter (Request, myresponse);//Take out the data in the cache, compress and then call the browser        byteOut[] = Myresponse.getbuffer (); System.out.println ("Original size:"+ out.length); Bytearrayoutputstream bout =NewBytearrayoutputstream ();//Compress the data in the output streamGzipoutputstream Gout =NewGzipoutputstream (bout);        Gout.write (out); Gout.close ();byteGzip[] = Bout.tobytearray (); System.out.println ("Size after compression:"+ gzip.length); Response.setheader ("Content-encoding","gzip");        Response.setcontentlength (gzip.length);    Response.getoutputstream (). write (gzip); }@Override     Public void Destroy() {System.out.println ("----Filter Destruction----"); }}class BufferResponse extends httpservletresponsewrapper{PrivateBytearrayoutputstream bout =NewBytearrayoutputstream ();PrivatePrintWriter PW;PrivateHttpServletResponse response; Public BufferResponse(HttpServletResponse response) {Super(response); This. Response = response; }@Override     PublicServletoutputstreamGetoutputstream()throwsIOException {return NewMyservletoutputstream (bout); }@Override     PublicPrintWritergetwriter()throwsIOException {pw =NewPrintWriter (NewOutputStreamWriter (bout, This. response.getcharacterencoding ()));returnpw } Public byte[]GetBuffer(){Try{if(pw!=NULL) {pw.close (); }if(bout!=NULL) {Bout.flush ();returnBout.tobytearray (); }return NULL; }Catch(Exception e) {Throw NewRuntimeException (e); }}}class Myservletoutputstream extends servletoutputstream{PrivateBytearrayoutputstream bout; Public Myservletoutputstream(Bytearrayoutputstream Bout) { This. bout = bout; }@Override     Public void Write(intbthrowsIOException { This. Bout.write (b); }}

3. Modify Web. xml

<filter>      <description>Configure Compression filters</Description>      <filter-name>Gzipfilter</filter-name>      <filter-class>Com.filter.EasyResponseGzipFilter</filter-class>  </filter>  <!--The contents of the JSP file's output are compressed by the compression filter before output--  <filter-mapping>      <filter-name>Gzipfilter</filter-name>      <url-pattern>*.jsp</url-pattern>      <!--for redirection or steering JSP page interception, via Request.getrequestdispatcher () in servlet. Forward ( )--      <dispatcher>FORWARD</Dispatcher>      <!--for direct URL access to the JSP page interception, the filter is the default way to intercept request-->      <dispatcher>REQUEST</Dispatcher>  </filter-mapping>  The output of the <!--JS file is compressed by the compression filter before output--  <filter-mapping>      <filter-name>Gzipfilter</filter-name>      <url-pattern>*.js</url-pattern>  </filter-mapping>  <!--The contents of the output of the CSS file are compressed by the compression filter before output--  <filter-mapping>      <filter-name>Gzipfilter</filter-name>      <url-pattern>*.css</url-pattern>  </filter-mapping>  <!--the output of an HTML file is compressed by a compressed filter before output--  <filter-mapping>      <filter-name>Gzipfilter</filter-name>      <url-pattern>*.html</url-pattern>  </filter-mapping> 

4. Final running result
Enter URL Test address: http://localhost:8080/webStudy/index.jsp
Index.jsp is the file I created myself through MyEclipse to create the Web app without making any changes.

The results of the operation are as follows:
Original size: 625
Size after compression: 354

Better than a bad memory. 33-Compress response body content with Java filters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.