public class WordFilter implements Filter{
protected FilterConfig filterConfig;
public void init(FilterConfig config) throws ServletException{
this.filterConfig=config;
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws
IOException,ServletException{
PrintWriter out=response.getWriter();
CharResponseWrapper wrapper=new CharResponseWrapper((HttpServletResponse)response);
chain.doFilter(request,wrapper);
String resStr=wrapper.toString();
String newStr="";
if(resStr.indexOf("is")>0){
newStr=resStr.replaceAll("is","***");
}
out.println(newStr);
}
public void destroy(){
this.filterConfig=null;
}
public void setFilterConfig(final FilterConfig filterConfig){
this.filterConfig=filterConfig;
}
}
在程序中,out.println(str)就是输出的网页内容,这个字符串在程序中重写过,把网页中的字符串is替换为***。
最后在web.xml文件中配置这个过滤器:
web.xml文件
encoding="ISO-8859-1"?>
/p>
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
WordFilter
examples.WordFilter
WordFilter
/index.jsp
这个过滤器应用到index.jsp
%>
WelcomeThis is a String!
下面是运行结果: