防止SQL注入


參考: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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM