1 18 package filters.gzip; 19 20 import java.io.IOException ; 21 import java.util.Enumeration ; 22 23 import javax.servlet.Filter ; 24 import javax.servlet.FilterChain ; 25 import javax.servlet.FilterConfig ; 26 import javax.servlet.ServletContext ; 27 import javax.servlet.ServletException ; 28 import javax.servlet.ServletRequest ; 29 import javax.servlet.ServletResponse ; 30 import javax.servlet.http.HttpServletRequest ; 31 import javax.servlet.http.HttpServletResponse ; 32 33 40 public class GzipFilter implements Filter { 41 42 private static final String ACCEPT_ENCODING = "Accept-Encoding"; 43 44 private ServletContext context; 45 46 public void init(FilterConfig config) throws ServletException { 47 this.context = config.getServletContext(); 48 } 49 50 public void destroy() { 51 this.context = null; 52 } 53 54 public void doFilter(ServletRequest request, ServletResponse response, 55 FilterChain chain) throws IOException , ServletException { 56 Enumeration headers = ((HttpServletRequest ) request).getHeaders(ACCEPT_ENCODING); 57 boolean acceptsGzipEncoding = false; 58 while (headers.hasMoreElements() && !acceptsGzipEncoding) { 59 acceptsGzipEncoding = (((String ) headers.nextElement()).indexOf("gzip") != -1); 60 } 61 if (acceptsGzipEncoding) { 62 GzipResponseWrapper encodedResponse = new GzipResponseWrapper( 63 (HttpServletResponse ) response, this.context); 64 chain.doFilter(request, encodedResponse); 65 encodedResponse.close(); 66 } else { 67 chain.doFilter(request, response); 68 } 69 } 70 } 71 | Popular Tags |