用过滤器过滤全站非法字符

package cn.lfd.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

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.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/*
 * 用过滤器过滤全站非法字符
 */
public class DirtyWordFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		MyDirtyWordRequest myRequest = new MyDirtyWordRequest(request);//new 出一个增强后的HttpServletRequest
		chain.doFilter(myRequest, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
//用包装模式对HttpServletRequest进行增强
class MyDirtyWordRequest extends HttpServletRequestWrapper{
	//定义好非法字符集合
	private List<String> dirtywrods = Arrays.asList(new String[]{"sb","操蛋","畜生"});

	public MyDirtyWordRequest(HttpServletRequest request) {
		super(request);
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if(value==null) {
			return null;
		}
		for(String dirtyword:dirtywrods) {//对非法字符集合进行遍历
			if(value.contains(dirtyword)) {//如果数据中含有非法字符
				value = value.replace(dirtyword, "***");//用***代替
			}
		}
		return value;//返回代替后的数据
	}
}

注意:

过滤器写好后一定要在web.xml文件下配置一下,否则没有效果

你可能感兴趣的:(filter,javaweb,过滤器,过滤非法字符)