package servlt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GizpServlt extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("abc.......");
		 String str="nsdhfjvndknhguris湖gdfdffwqdsacdggtrhhjzx" +
			  		"南城市学院湖南城市学院湖南城市学fffffffffffffzfff院gtsrgt" +
			  		"湖南城市学院ytdewfdsffrsgs湖南城市学院湖南城市学院vnbvnhgnh" +
			  		"湖南城市学院dsfdxgxxfhj湖南城市学院湖南城市学院brefdcdsadjh" +
			  		"湖南城市学院欢迎来到浑南城市血雨啊第底部房地产商的哇发啊防风固沙提高调查" +
			  		"三方广泛的撒釜底抽薪出现swdszghyt幸福的在深圳工作的复活石头人是不是认识" ;
		 byte src[]=str.getBytes("UTF-8");
		 System.out.println("压缩前的长度:"+src.length);
		 
		 ByteArrayOutputStream bout=new ByteArrayOutputStream();//内存流;
		 GZIPOutputStream gzipout=new GZIPOutputStream(bout);
		 gzipout.write(src);//把src数组写入到压缩bout中
		 gzipout.close();//刷缓存;
		 byte dest[]=bout.toByteArray();//把源数据压缩成目标数据;
		 System.out.println("压缩后的长度:"+dest.length);
		
		 /* 告诉浏览器,当前用resp写出的内容不要缓存
			resp.setHeader("Expires", "-1");
			resp.setHeader("Cache-control", "no-cache");
			resp.setHeader("Pragma", "no-cache");
		*/
		 
		 resp.setContentType("text/html;charset=utf-8");
		 //输出压缩数据时,必须设置相应头;
		 resp.setHeader("Content-Encoding", "gzip");//这个gzip是要跟web.xml里面的 <url-pattern>里面设置的名字一样,才能连接到服务器中;
		 OutputStream out=resp.getOutputStream();
		 out.write(dest);	 
	}
}
原文:http://www.cnblogs.com/1314wamm/p/5917446.html