JSP中过滤器的设置
package com.filter; import java.io.IOException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern; 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.HttpServletResponse; public class SQLFilter implements Filter{ static String reg ="(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|DBMS_XMLQUERY.GETXML|DBMS_XMLQUERY.NEWCONTEXT)\\b|"
+ "\\b(?:script|eval|vbscript|javascript|base)\\b|(?:[`]+)|(?:<script>)|(?:\\b(?:onload|onerror|onunload|onclick|ondblclick)\\b)";
// ?: 只匹配,不缓存匹配到的内容;
// /\\*相当于匹配/*
// . 表示任意可显示字符
// \\b()\\b 表示单独匹配单词
// [\\n\\r] 表示只要符合其中的任意一个;[1-9]也可以是一个范围; static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub } @Override
public void doFilter(final ServletRequest req, final ServletResponse resp,
final FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse)resp; String uri = request.getRequestURI(); Set<String> passURIs = new HashSet<String>();
passURIs.add("/dsp71025/kdxt/kysj/qlysscyj.jsp");
passURIs.add("/dsp71025/kdxt/kysj/lkfsl.jsp"); if(passURIs.contains(uri)){ }else{
Map<String,String[]> params = request.getParameterMap(); for(String pk : params.keySet()){
String[] value = params.get(pk);
if(!isValid(value)){
System.out.println("参数:"+pk+"的值:"+Arrays.toString(value)+"不合法!");
return ;
}
}
} chain.doFilter(request, response); } private boolean isValid(String[] pValue){ if(pValue != null && pValue.length > 0){ for(int i=0;i<pValue.length;i++){
String s = pValue[i];
System.out.println("解码前的值: "+s);
//"%"编码后为"%25"
s = URLDecoder.decode(s.replaceAll("%", "%25"));
System.out.println("解码后的值: "+s);
if (sqlPattern.matcher(s).find()) {
return false;
}
} }
return true; } }