。扩展javax.servlet.http.HttpServletResponseWrapper。
2)提供一个缓存输出的PrintWriter。重载getWriter方法,返回一个保存发送给它的所 有东西的PrintWriter,并把结果存进一个可以稍后访问的字段中。
3)传递该包装器给doFilter。此调用是合法的,因为HttpServletResponseWrapper实现 HttpServletResponse。
4)提取和修改输出。在调用FilterChain的doFilter方法后,原资源的输出只要利用步骤 2中提供的机制就可以得到。只要对你的应用适合,就可以修改或替换它。
5)发送修改过的输出到客户机。因为原资源不再发送输出到客户机(这些输出已经存放 到你的响应包装器中了),所以必须发送这些输出。这样,你的过滤器需要从原响应对象中 获得PrintWriter或OutputStream,并传递修改过的输出到该流中。
Servlet过滤器介绍之实用过滤器(3)
时间:2011-04-09 51cto zhangjunhd
7.2 一个可重用的响应包装器
下例程序给出了一个包装器,它可用于希望过滤器修改资源的输出的大多数应用中。 CharArrayWrapper类重载getWriter方法以返回一个PrintWriter,它累积一个大字符数组中 的所有东西。开发人员可利用toCharArray(原始char[])或toString(从char[]得出的一个 String)方法得到这个结果。
CharArrayWrapper.java
package com.zj.sample;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* A response wrapper that takes everything the client would normally
* output and saves it in one big character array.
*/
public class CharArrayWrapper extends HttpServletResponseWrapper {
private CharArrayWriter charWriter;
/**
* Initializes wrapper.
* <P>
* First, this constructor calls the parent constructor. That call
*is crucial so that the response is stored and thus setHeader, *setStatus, addCookie, and so forth work normally.
* <P>
* Second, this constructor creates a CharArrayWriter that will
* be used to accumulate the response.
*/
public CharArrayWrapper(HttpServletResponse response) {
super(response);
charWriter = new CharArrayWriter();
}
/**
* When servlets or JSP pages ask for the Writer, don''t give them
* the real one. Instead, give them a version that writes into
* the character array.
* The filter needs to send the contents of the array to the
* client (perhaps after modifying it).
*/
public PrintWriter getWriter() {
return (new PrintWriter(charWriter));
}
/**
* Get a String representation of the entire buffer.
* <P>
* Be sure <B>not</B> to call this method multiple times on the same
* wrapper. The API for CharArrayWriter does not guarantee that it
* "remembers" the previous value, so the call is likely to make
* a new String every time.
*/
public String toString() {
return (charWriter.toString());
}
/** Get the underlying character array. */
public char[] toCharArray() {
return (charWriter.toCharArray());
}
}
7.3 替换过滤器
这里展示前一节中给出的CharArrayWrapper的一个常见的应用:更改一个多次出现的 |