[java]代码库
package com.bingyang.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class WordFilter implements Filter
{
private List<String> unString;
/**
* 过滤器初始化,将要屏蔽的字符串都加载到list集合中.
*/
public void init(FilterConfig filterConfig) throws ServletException
{
unString = new ArrayList<String>();
String aa="日,tmd,TMD,滚蛋,系统";
StringTokenizer st = new StringTokenizer(aa, ",");
while(st.hasMoreElements()){
unString.add(st.nextElement().toString());
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
request.setCharacterEncoding("utf-8");
String content = request.getParameter("content");//需要过滤的参数
if(content!=null){
for (int i = 0; i < unString.size(); i++)
{
String strIllegal = unString.get(i);
if (content.indexOf(strIllegal) >= 0)
{
content = content.replaceAll(strIllegal, "*");//非法字符替换成*
}
request.setAttribute("content", content);//为request设置属性保存修改后的值
}
}
chain.doFilter(request, response);
}
public void destroy()
{
//System.out.println("过滤器销毁");
}
}//源代码片段来自云代码http://yuncode.net