Package com;
Import java.io.IOException;
Import java.util.Enumeration;
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;
Filter for filtering SQL keywords
public class Sqlfilter implements Filter {
public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {
HttpServletRequest req = (httpservletrequest) request;
HttpServletResponse res = (httpservletresponse) response;
Get all request parameter names
Enumeration params = Req.getparameternames ();
String sql = "";
while (Params.hasmoreelements ()) {
Get the name of the parameter
String name = Params.nextelement (). toString ();
System.out.println ("name===========================" + name + "--");
Get parameter corresponding value
string[] Value = req.getparametervalues (name);
for (int i = 0; i < value.length; i++) {
sql = SQL + value[i];
}
}
System.out.println ("Matched string:" +sql);
if (sqlvalidate (SQL)) {
Res.sendredirect ("error.jsp");
} else {
Chain.dofilter (req, res);
}
}
Check
Protected static Boolean sqlvalidate (String str) {
str = str.tolowercase ();//Unified to lowercase
String badstr = "And|exec";
String badstr = "' |and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare| Sitename|net User|xp_cmdshell|or|like ";
/*string badstr = "' |and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" +
"Information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +
"Chr|mid|master|truncate|char|declare|or|;| -|--|+|,|like|//|/|%| #"; *///filter out the SQL keyword, you can manually add
string[] Badstrs = Badstr.split ("\\|");
for (int i = 0; i < badstrs.length; i++) {
if (Str.indexof (Badstrs[i])!=-1) {
System.out.println ("Match to:" +badstrs[i]);
return true;
}
}
return false;
}
public void init (Filterconfig filterconfig) throws Servletexception {
throw new Unsupportedoperationexception ("not supported yet.");
}
public void Destroy () {
throw new Unsupportedoperationexception ("not supported yet.");
}
}
JSP uses filters to prevent SQL injection