目标 串为某个替代串的过滤器。
Servlet过滤器介绍之实用过滤器(4)
时间:2011-04-09 51cto zhangjunhd
7.3.1 通用替换过滤器
ReplaceFilter.java给出一个过滤器,它在CharArraryWrapper中包装响应,传递该包装 器到FilterChain对象的doFilter方法中,提取一个给出所有资源的输出的String型值,用一 个替代串替换某个目标串的所有出现,并发送此修改过的结果到客户机。
关于这个过滤器,有两件事情需要注意。首先,它是一个抽象类。要使用它,必须建立一 个提供getTargetString和getReplacementString方法的实现的子类。下一小节中给出了这种 处理的一个例子。其次,它利用一个较小的实用类(见FilterUtils.java)来进行实际的串 替换。你可使用新的常规表达式包而不是使用String和StringTokenizer中低级的和繁琐的方 法。
ReplaceFilter.java
package com.zj.sample;
import java.io.IOException;
import java.io.PrintWriter;
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.HttpServletResponse;
/**
* Filter that replaces all occurrences of a given string with a
* replacement.
* This is an abstract class: you <I>must</I> override the getTargetString
* and getReplacementString methods in a subclass.
* The first of these methods specifies the string in the response
* that should be replaced. The second of these specifies the string
* that should replace each occurrence of the target string.
*/
public abstract class ReplaceFilter implements Filter {
private FilterConfig config;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
CharArrayWrapper responseWrapper = new CharArrayWrapper(
(HttpServletResponse) response);
// Invoke resource, accumulating output in the wrapper.
chain.doFilter(request, responseWrapper);
// Turn entire output into one big String.
String responseString = responseWrapper.toString();
// In output, replace all occurrences of target string with replacement
// string.
responseString = FilterUtils.replace(responseString, getTargetString (),
getReplacementString());
// Update the Content-Length header.
updateHeaders(response, responseString);
PrintWriter out = response.getWriter();
out.write(responseString);
}
/**
* Store the FilterConfig object in case subclasses want it.
*/
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
protected FilterConfig getFilterConfig() {
return (config);
}
public void destroy() {
}
/**
* The string that needs replacement.
*Override this method in your subclass.
*/
public abstract String getTargetString();
/**
* The string that replaces the target. Override this method in
* your subclass.
*/
public abstract
|