jdbc防止sql注入方法總結
阿新 • • 發佈:2019-01-03
參考: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