参考:http://hi.baidu.com/wangyue06/item/c00c824b35cf740ae835049c
1.传统JDBC,采用PreparedStatement 。预编译语句集,内置了处理SQL注入的能力
String sql= "select * from users where username=? and password=?"; //如果把?改为:username1,按参数名绑定 PreparedStatement preState = conn.prepareStatement(sql); preState.setString(1, userName); //则此处变为.setString("username1",username) preState.setString(2, password); ResultSet rs = preState.executeQuery();
2. 采用正则表达式,将输入的所有特殊符号转换为空格或其他字符
public static String TransactSQLInjection(String str) { return str.replaceAll(".*([';]+|(--)+).*", " "); // 我认为 应该是return str.replaceAll("([';])+|(--)+","");-->这是原作者的注释,个人不是很赞同。 } userName=TransactSQLInjection(userName); password=TransactSQLInjection(password); String sql="select * from users where username='"+userName+"' and password='"+password+"' "; Statement sta = conn.createStatement(); ResultSet rs = sta.executeQuery(sql);
参考:http://blog.csdn.net/fufengrui/article/details/7740288
3. JAVA Web中,编写Fileter,实现对renquest请求中参数的不合法字符替换
for(String word : invalidsql){ if(word.equalsIgnoreCase(value) || value.contains(word)){ if(value.contains("<")){ value = value.replace("<", "<"); //这个个人认为括号中第二个<应该替换成其他符号 } if(value.contains(">")){ value = value.replace(">", ">"); } request.getSession().setAttribute("sqlInjectError", "the request parameter \""+value+"\" contains keyword: \""+word+"\""); response.sendRedirect(request.getContextPath()+error); return; } }
4.hibernate 参考:http://www.cnblogs.com/yhason/archive/2012/06/07/2540840.html