在很多时候,网页中会包含一些服务器不想展现给用户的内容,服务器端需要先对这些内容过滤。
通常可以使用过滤器Filter进行敏感字符过滤。过滤器捕捉页面的响应内容,并缓存,然后将其中的敏感字替换成别的字。首先建立一个类来接收页面的响应内容,如下:
package examples;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CharResponseWrapper extends HttpServletResponseWrapper{
private CharArrayWriter output;
public String toString(){
return output.toString();
}
public CharResponseWrapper(HttpServletResponse response){
super(response);
output=new CharArrayWriter();
}
public PrintWriter getWriter(){
return new PrintWriter(output);
}
}
这个类重载了toString方法,由此可以将网页中的内容转化为字符串,然后在过滤器
的类中重写响应的内容,把敏感字去掉。如下是过滤器的代码:
package examples;
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文件
<?xml version="1.0" encoding="ISO-8859-1"?>
web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
这个过滤器应用到index.jsp
<%@ page contentType="text/html; charset=GBK" %>
<head>
下面是运行结果:
↑返回目录
前一篇: 用Servlet开发和配置过滤器(字符集设置)
后一篇: 使用xmlhttp和Java session监听改善站内消息系统