javaweb登錄預防SQL注入的方法:
1.可采用PreparedStatement進行預編譯,例如:
String sql = "select* from users where username=? and password=?";
Connection conn = null;
PreparedStatement state = null;
ResultSet result;
conn = JdbcUtil.getConnection();
System.out.println(sql);
try {
state = conn.prepareStatement(sql);
state.setString(1, userName);
state.setString(2, passWord);
result = state.executeQuery();
2.使用正則表達式過濾傳入的參數,例如:
要引入的包:
import java.util.regex.*;
正則表達式:
private String CHECKsql = “^(.+)\\sand\\s(.+)|(.+)\\sor(.+)\\s$”;
判斷是否匹配:
Pattern.matches(CHECKsql,targerStr);
3.對字符串進行過濾,例如:
public static boolean sql_inj(String str)
{
String inj_str = "'|and|exec|insert|select|delete|update|
count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
String inj_stra[] = split(inj_str,"|");
for (int i=0 ; i < inj_stra.length ; i++ )
{
if (str.indexOf(inj_stra[i])>=0)
{
return true;
}
}
return false;
}
4.使用javascript在客戶端進行不安全字符屏蔽,例如JSP頁面判斷代碼:
function check(a){return 1;
fibdn = new Array (”‘” ,”\\”,”/”);
i=fibdn.length;
j=a.length;
for (ii=0; ii<i; ii++)
{ for (jj=0; jj<j; jj++)
{ temp1=a.charAt(jj);
temp2=fibdn[ii];
if (tem’; p1==temp2)
{ return 0; }
}
}
return 1;
}