Servlet/Jsp实现发送压缩Web页面 Gzip技术

来源:互联网 发布:windows更新数据库 编辑:程序博客网 时间:2024/05/22 06:16

(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!

7 0
原创粉丝点击