(1) What words do not say, meaning is very simple to achieve the compression of the page sent! It is said that for longer pages can be improved hundreds of times times Oh!
(2) Note: Not all of the browser support compressed page send and receive, so to use code to verify, if you can send can not
is sent according to normal;
(That is: Check the accept-encoding header in the HTTP header, check that his hand contains an item about gzip, if supported, it uses PrintWriter
Install Gzipoutputstream, do not support the normal sending page, while adding a feature to prohibit page compression! )
(3) Servlet showing the page
Package Com.lc.ch04gzip;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class LongServlet Extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {response.setcontenttype ("text/html"); PrintWriter out;if (gziputilities.isgzipsupported (request) &&! gziputilities.isgzipdisabled (Request)) {out = Gziputilities.getgzipwriter (response); Response.setheader (" Content-encoding "," gzip ");} else {out = Response.getwriter ();} String DocType = "<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.0" + "transitional//en\" >\n "; String title = "Long page"; Out.println (DocType + "
(4) class for handling compressionpackage Com.lc.ch04gzip;import Java.io.ioexception;import Java.io.printwriter;import Java.util.zip.GZIPOutputStream; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class gziputilities {public static Boolean isgzipsupported (HttpServletRequest request) {String encodings = Reque St.getheader ("accept-encoding"); Return ((encodings! = null) && (Encodings.indexof ("gzip")! =-1)); public static Boolean isgzipdisabled (HttpServletRequest request) {String flag = Request.getparameter ("Disab Legzip "); Return ((flag! = null) && (!flag.equalsignorecase ("false"))); } public static PrintWriter Getgzipwriter (HttpServletResponse response) throws IOException {return (new PRINTW Riter (New Gzipoutputstream (Response.getoutputstream ())); }}
(5) Demo effect: (The effect is very good but no comparison but should be able to general picture does not need to compress!) )
Ok!
SERVLET/JSP implementing the Send Compressed Web page gzip Technology