使用GZIP压缩的方式向客户端传输响应数据

1, 工具类:测试客户端是否支持GZIP编码压缩方式 & 获得支持GZIP的PrintWriter对象

package freebsd;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Utilities {
/*
* 测试客户端浏览器是否支持gzip的编码方式
*/
public static boolean isSurpported(HttpServletRequest request)
{
   String encodingString = request.getHeader("Accept-Encoding");
   return (encodingString!=null) && (encodingString.indexOf("gzip")!=-1);
}
/*
* 取得一个压缩的PrintWriter
*/
public static PrintWriter getWriter(HttpServletResponse response) throws IOException
{
   ServletOutputStream sos = response.getOutputStream();
   GZIPOutputStream gzipos = new GZIPOutputStream(sos);
   return new PrintWriter(gzipos);
}

}
2,Servlet类,产生一个长字符串,然后在html页面中请求该servlet:

import freebsd.*;

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;

/**
* Servlet implementation class ServletGzip
*/
public class ServletGzip extends HttpServlet {
private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletGzip() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   response.setContentType("text/html");
   response.setStatus(response.SC_OK);
   PrintWriter out;
   if(Utilities.isSurpported(request))
   {
    out = Utilities.getWriter(response);

   //协议: 通知客户端使用gzip这种压缩方式而不是其它的,如compress
    response.setHeader("Content-Encoding", "gzip");
   }else {
    out = response.getWriter();
   }
   StringBuilder sBuilder = new StringBuilder();
   for(int i=0; i!=5000; ++i)
   {
    sBuilder.append("Printing the long string... ...!");
   }
   out.println(sBuilder);
out.close();
}
}

你可能感兴趣的:(j2ee-web)