java
package coreservlets.filters;
import java.io.*;
import java.util.zip.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Filter that compresses output with gzip
* (assuming that browser supports gzip).
*/
public class CompressionFilter implements Filter {
private FilterConfig config;
/** If browser does not support gzip, invoke resource
* normally. If browser
does support gzip,
* set the Content-Encoding response header and
* invoke resource with a wrapped response that
* collects all the output. Extract the output
* and write it into a gzipped byte array. Finally,
* write that array to the client's output stream.
*/
Chapter 5 ?– Servlet and JSP Filters 248
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
if (!isGzipSupported(req)) {
// Invoke resource normally.
chain.doFilter(req,res);
} else {
// Tell browser we are sending it gzipped data.
res.setHeader("Content-Encoding", "gzip");
// Invoke resource, accumulating output in the wrapper.
StringWrapper responseWrapper =
new StringWrapper(res);
chain.doFilter(req,responseWrapper);
// Make a writer that compresses data and puts
// it into a byte array.
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream();
GZIPOutputStream zipOut =
new GZIPOutputStream(byteStream);
OutputStreamWriter tempOut =
new OutputStreamWriter(zipOut);
// Compress original output and put it into byte array.
Pages:
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300