標籤:servletjsp實現發送壓縮web頁 gzip技術 頁面文本壓縮 servlet 壓縮
(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 = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "+ "Transitional//EN\">\n";String title = "Long Page";out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title+ "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n"+ "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n");String line = "Bfsdfdsfdsflah, blfsdfdsfah, blasfdsdfh, blsdfdsfah, bldfsdfsdfah. "+ "Yaddsfdsdfa, ysfdsdfadda, yadsdfsdfdsda, yasdfsdfdsfdda.";for (int i = 0; i < 10000; i++) {out.println(line);}out.println("</BODY></HTML>");out.close(); // Needed for gzip; optional otherwise.}}
(4)處理壓縮的類
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!
Servlet/Jsp實現發送壓縮Web頁面 Gzip技術