web项目特殊字符限制 过滤器实例
import java.io.IOException;
import java.util.Map;
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 IllegalCharacterFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("过滤器.....");
req.setCharacterEncoding("utf-8");
res.setCharacterEncoding("utf-8");
String[] strBadChar = {
"and"
,"exec"
,"insert"
,"delete"
,"update"
,"count"
,"*"
,"%"
,"\'"
,"\""
,"master"
,"truncate"
,"declare"
,"SiteName"
,"net user"
,"xp_cmdshell"
,"/add"
,"exec master.dbo.xp_cmdshell"
,"net localgroup administrators"
};
Map pamamap=req.getParameterMap();
Object[] obj = pamamap.keySet().toArray();
boolean state = true;
if(!pamamap.isEmpty()){
for(int i=0;i<obj.length;i++){
String content=req.getParameter(obj[i].toString());
System.out.println("验证:" +content);
if(content != null){
for(String str : strBadChar){
if(content.toUpperCase().indexOf(str.toUpperCase()) != -1){
state = false;
req.setAttribute("err", "含有禁止的字符:" + str);
System.out.println("参数[" + content + "]含有特殊字符[" + str +"]");
break;
}
}
}
if(!state){
break;
}
System.out.println("key:" + obj[i].toString());
System.out.println("content:" + content);
System.out.println("================");
}
}
System.out.println(state);
if(state){
chain.doFilter(req, res);
}else{
req.getRequestDispatcher("/illegalErr.jsp").forward(req, res);
}
}
public void init(FilterConfig arg0) throws ServletException {
}