,以防子类需要访问servlet环境或过滤器名。destory方法体为空。
2)包装的响应对象。DoFilter方法将ServletResponse对象包装在一个CharArrayWrapper 中,并传递此包装器到FilterChain对象的doFilter方法上。在此调用完成后,所有其他过滤 器和最终资源都已执行,且输出结果位于包装器之内。这样,原doFilter提取一个代表所有 资源的输出的字符数组。如果客户机指出它支持压缩(即,以gzip作为Accept-Encoding头的 一个值),则过滤器附加一个GZIPOutputStream到ByteArrayOutputStream上,将字符数组复 制到此流中,并设置Content-Encoding响应头为gzip。如果客户机不支持gzip,则将未修改 过的字符数组复制到ByteArrayOutputStream。最后,doFilter通过将整个字符数组(可能是 压缩过的)写到与original响应相关的OutputStream中,发送结果到客户机。
Servlet过滤器介绍之实用过滤器(7)
时间:2011-04-09 51cto zhangjunhd
3)对LongServlet进行注册。
CompressionFilter.java
package com.zj.sample;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.zip.GZIPOutputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 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
* <I>does</I> 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.
*/
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.
CharArrayWrapper responseWrapper = new CharArrayWrapper(res);
chain.doFilter(req, responseWrapper);
// Get character array representing output.
char[] responseChars = responseWrapper.toCharArray();
// Make a writer that compresses data and puts it into a byte array.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
GZIPOutputStream zipOut = new GZIPOutputStream(byteStream);
OutputStreamWriter tempOut
|