1 25 26 package net.killingar.servlet.filter; 27 28 29 import javax.servlet.FilterChain ; 30 import javax.servlet.ServletRequest ; 31 import javax.servlet.ServletResponse ; 32 import javax.servlet.http.HttpServletResponse ; 33 import java.io.ByteArrayOutputStream ; 34 import java.io.OutputStream ; 35 import java.util.zip.GZIPOutputStream ; 36 37 38 public class GZipFilter extends GenericFilter 39 { 40 public GZipFilter() 41 { 42 } 43 44 45 public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain) throws java.io.IOException , javax.servlet.ServletException 46 { 47 GenericResponseWrapper wrapper = new GenericResponseWrapper((HttpServletResponse )response); 48 chain.doFilter(request, wrapper); 49 OutputStream out = response.getOutputStream(); 50 51 52 if (!request.getProtocol().equals("HTTP/1.0") && !cached(wrapper) && !included(request)) 53 { 54 ByteArrayOutputStream compressed = new ByteArrayOutputStream (); 55 GZIPOutputStream gzout = new GZIPOutputStream (compressed); 56 gzout.write(wrapper.getData()); 57 gzout.close(); 58 59 60 HttpServletResponse httpResponse = (HttpServletResponse )response; 61 httpResponse.setHeader("Content-Encoding","gzip"); 62 out.write(compressed.toByteArray()); 63 response.setContentLength(compressed.size()); 64 } 65 else 66 { 67 out.write(wrapper.getData()); 68 } 69 } 70 71 72 protected boolean included(ServletRequest request) 73 { 74 return null != request.getAttribute("javax.servlet.include.request_uri"); 75 } 76 77 78 protected boolean cached(GenericResponseWrapper wrapper) 79 { 80 return !(wrapper.getData().length > 0); 81 } 82 } | Popular Tags |