Java 防sql注入


  1. package com.cssweb.webcall.util;  
  2.   
  3. //: 防止一般SQL注入   
  4. //  调用方法:PreventInfusion.sqlInfusion(str);   
  5. public class PreventInfusion {  
  6.     private static final String inj_str = "'@and@exec@insert@select@delete@update@count@*@%@chr@mid@master@truncate@char@declare@;@or@lock table@grant@drop@ascii@-@+@,";  
  7.       
  8.     private static String strReplace(String str, String restr) {  
  9.         return str.replace(restr, "");  
  10.     }  
  11.       
  12.     private static String dealNull(String str) {  
  13.         String returnstr = null;  
  14.         if (str == null)  
  15.             returnstr = "";  
  16.         else  
  17.             returnstr = str;  
  18.         return returnstr;  
  19.     }  
  20.       
  21.     public static String sqlInfusion(String str) {  
  22.         String inj_stra[] = inj_str.split("@");  
  23.         str = dealNull(str);  
  24.         str = str.toLowerCase();  
  25.         for (int i = 0; i < inj_stra.length; i++) {  
  26.             if (str.indexOf(inj_stra[i]) >= 0) {  
  27.                 str = strReplace(str, inj_stra[i]);  
  28.             }  
  29.         }  
  30.         return str;  
  31.     }  
  32.       
  33.     public static void main(String[] args) {  
  34.         System.out.println(sqlInfusion(""));  
  35.         System.out.println(sqlInfusion("null"));  
  36.         System.out.println(sqlInfusion(null));  
  37.         System.out.println(sqlInfusion("'adm'in,SELEct;"));  
  38.     }  
  39. }///:~  

相关内容