1 64 65 package net.myvietnam.mvncore.servlet.filter; 66 67 import java.io.IOException ; 68 import java.util.Enumeration ; 69 70 import javax.servlet.*; 71 import javax.servlet.http.HttpServletRequest ; 72 import javax.servlet.http.HttpServletResponse ; 73 74 import org.apache.commons.logging.Log; 75 import org.apache.commons.logging.LogFactory; 76 77 78 86 87 public class CompressionFilter implements Filter{ 88 89 private static Log log = LogFactory.getLog(CompressionFilter.class); 90 91 95 private FilterConfig config = null; 96 97 100 private int minThreshold = 128; 101 102 103 106 protected int compressionThreshold; 107 108 111 113 118 119 public void init(FilterConfig filterConfig) { 120 121 config = filterConfig; 122 if (filterConfig != null) { 123 130 String str = filterConfig.getInitParameter("compressionThreshold"); 131 if (str!=null) { 132 compressionThreshold = Integer.parseInt(str); 133 if (compressionThreshold != 0 && compressionThreshold < minThreshold) { 134 log.info("compressionThreshold should be either 0 - no compression or >= " + minThreshold); 135 log.info("compressionThreshold set to " + minThreshold); 136 compressionThreshold = minThreshold; 137 } 138 } else { 139 compressionThreshold = 0; 140 } 141 142 } else { 143 compressionThreshold = 0; 144 } 145 146 } 147 148 151 public void destroy() { 152 153 this.config = null; 154 155 } 156 157 173 174 public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) 175 throws IOException , ServletException { 176 190 request.setCharacterEncoding("utf-8"); 191 if (compressionThreshold == 0) { 192 chain.doFilter(request, response); 194 return; 195 } 196 boolean supportCompression = false; 197 if (request instanceof HttpServletRequest ) { 198 200 String s = request.getParameter("gzip"); 202 if ("false".equals(s)) { 203 chain.doFilter(request, response); 205 return; 206 } 207 208 Enumeration e = 209 ((HttpServletRequest )request).getHeaders("Accept-Encoding"); 210 while (e.hasMoreElements()) { 211 String name = (String )e.nextElement(); 212 if (name.indexOf("gzip") != -1) { 213 supportCompression = true; 215 } else { 216 } 218 } 219 } 220 221 if (!supportCompression) { 222 chain.doFilter(request, response); 224 return; 225 } else { 226 if (response instanceof HttpServletResponse ) { 227 CompressionServletResponseWrapper wrappedResponse = 228 new CompressionServletResponseWrapper((HttpServletResponse )response); 229 wrappedResponse.setCompressionThreshold(compressionThreshold); 232 try { 234 chain.doFilter(request, wrappedResponse); 235 } finally { 236 wrappedResponse.finishResponse(); 237 } 238 return; 239 } 240 } 241 } 242 243 249 public void setFilterConfig(FilterConfig filterConfig) { 250 init(filterConfig); 251 } 252 253 257 public FilterConfig getFilterConfig() { 258 return config; 259 } 260 261 } 262 263 | Popular Tags |