过滤器:
1 public class Gzip implements Filter { 2 3 public void destroy() {} 4 5 public void doFilter(ServletRequest request, ServletResponse response, 6 FilterChain chain) throws IOException, ServletException { 7 HttpServletResponse resp=(HttpServletResponse) response; 8 MyResp myResp=new MyResp(resp);//包装过的response 9 chain.doFilter(request, myResp);//放行 10 11 byte[] srcBytes= myResp.getSrcByte();//获取源数据 12 ByteArrayOutputStream bOutStream=new ByteArrayOutputStream();//目标容器 13 GZIPOutputStream zipOutStream=new GZIPOutputStream(bOutStream);//压缩工具 14 zipOutStream.write(srcBytes);//写到容器中 15 zipOutStream.close();//如果不关闭,会在缓存中,不写出 16 17 byte[] descByte=bOutStream.toByteArray(); 18 19 System.out.println("-------------------"); 20 System.out.println("压缩前:"+srcBytes.length); 21 System.out.println("压缩后:"+ descByte.length); 22 System.out.println("-------------------"); 23 24 //使用原生response输出 25 resp.setContentType("text/html;charset=utf-8"); 26 resp.setHeader("Content-Encoding", "Gzip"); 27 resp.setContentLength(srcBytes.length); 28 29 //输出 30 OutputStream out=resp.getOutputStream(); 31 out.write(descByte);//关闭 32 33 34 } 35 public void init(FilterConfig filterConfig) throws ServletException {} 36 37 } 38 39 class MyResp extends HttpServletResponseWrapper 40 { 41 private PrintWriter outWrite; 42 private ByteArrayOutputStream srcByte; 43 //获取原生数据 44 public byte[] getSrcByte() { 45 if(outWrite!=null)//如果不关闭流,不会显示,因为数据在缓存中,没有写出 46 { 47 outWrite.close(); 48 } 49 return srcByte.toByteArray(); 50 } 51 52 public MyResp(HttpServletResponse response) { 53 super(response); 54 55 } 56 57 //包装getWrite()方法,jsp页面输出内容使用的是response.getWriter().write("") 58 //所以要包装 59 @Override 60 public PrintWriter getWriter() throws IOException { 61 srcByte=new ByteArrayOutputStream();//输出的源数据 62 outWrite=new PrintWriter(new OutputStreamWriter(srcByte,"utf-8")); 63 return outWrite; 64 } 65 66 }
如果过滤器需要过滤Servlet,则需要用response.getWriter().write("")输出,否则不会被过滤
1 response.setContentType("text/html;charset=utf-8"); 2 String str="你好,同学;Hello World"; 3 PrintWriter writer=response.getWriter(); 4 writer.write(str); 5 writer.close();
如果Servlet中使用response.getOutputStream().write("")输出,则需要包装getOutputStream()方法
1 response.setContentType("text/html;charset=utf-8"); 2 String str="你好,同学;Hello World"; 3 String times=request.getParameter("times"); 4 int n=Integer.valueOf(times); 5 OutputStream out=response.getOutputStream(); 6 for (int i = 0; i < n; i++) { 7 out.write(str.getBytes("utf-8")); 8 } 9 out.close();
包装getOutputStream()方法
1 @Override 2 public ServletOutputStream getOutputStream() throws IOException { 3 srcByte =new ByteArrayOutputStream();//输出的源数据 4 ServletOutputStream out=new ServletOutputStream() { 5 @Override 6 public void write(int b) throws IOException { 7 srcByte.write(b); 8 } 9 }; 10 return out; 11 }