(1)什麼話都不說,意思很簡單 就是實現頁面的壓縮後發送!據說對於篇幅比較長的頁面可以提高幾百倍哦!
(2)注意事項:並不是所有的游覽器都支持壓縮頁面的發送與接收,所以要用代碼來檢驗,如果可以則發送不可以
則按照正常的發送;
(即是:在HTTP包頭中檢查 Accept-Encoding報頭,檢查他手否包含有關gzip的項,如果支持,它使用PrintWriter封
裝GZIPOutputStream,不支持的話則正常發送頁面,同時加上了一個功能 禁止頁面壓縮!)
(3)顯示頁面的servlet
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 = "\n"; String title = "Long Page"; out.println(docType + "\n" + "" + title + " \n" + "\n" + "" + title + "
\n"); String line = "Bfsdfdsfdsflah, blfsdfdsfah, blasfdsdfh, blsdfdsfah, bldfsdfsdfah. " + "Yaddsfdsdfa, ysfdsdfadda, yadsdfsdfdsda, yasdfsdfdsfdda."; for (int i = 0; i < 10000; i++) { out.println(line); } out.println(""); out.close(); // Needed for gzip; optional otherwise. } }
package 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 = request.getHeader("Accept-Encoding"); return((encodings != null) && (encodings.indexOf("gzip") != -1)); } public static boolean isGzipDisabled (HttpServletRequest request) { String flag = request.getParameter("disableGzip"); return((flag != null) && (!flag.equalsIgnoreCase("false"))); } public static PrintWriter getGzipWriter (HttpServletResponse response) throws IOException { return(new PrintWriter (new GZIPOutputStream (response.getOutputStream()))); } }(5)演示效果:(效果很好 不過沒有對比 不過應該可以 一般的圖片 不需要壓縮了!)
ok!