public class StringUtil {
public StringUtil() {
}
public static String replace(String str, String substr, String restr) {
String[] tmp = split(str, substr);
String returnstr = null;
if (tmp.length != 0) {
returnstr = tmp[0];
for (int i = 0; i < tmp.length - 1; i++)
returnstr = dealNull(returnstr) + restr + tmp[i + 1];
}
return dealNull(returnstr);
}
public static String[] split(String source, String div) {
int arynum = 0, intIdx = 0, intIdex = 0, div_length = div.length();
if (source.compareTo("") != 0) {
if (source.indexOf(div) != -1) {
intIdx = source.indexOf(div);
for (int intCount = 1;; intCount++) {
if (source.indexOf(div, intIdx + div_length) != -1) {
intIdx = source.indexOf(div, intIdx + div_length);
arynum = intCount;
} else {
arynum += 2;
break;
}
}
} else
arynum = 1;
} else
arynum = 0;
intIdx = 0;
intIdex = 0;
String[] returnStr = new String[arynum];
if (source.compareTo("") != 0) {
if (source.indexOf(div) != -1) {
intIdx = (int) source.indexOf(div);
returnStr[0] = (String) source.substring(0, intIdx);
for (int intCount = 1;; intCount++) {
if (source.indexOf(div, intIdx + div_length) != -1) {
intIdex = (int) source
.indexOf(div, intIdx + div_length);
returnStr[intCount] = (String) source.substring(intIdx
+ div_length, intIdex);
intIdx = (int) source.indexOf(div, intIdx + div_length);
} else {
returnStr[intCount] = (String) source.substring(intIdx
+ div_length, source.length());
break;
}
}
} else {
returnStr[0] = (String) source.substring(0, source.length());
return returnStr;
}
} else {
return returnStr;
}
return returnStr;
}
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;
}
private static String dealNull(String str) {
String returnstr = null;
if (str == null)
returnstr = "";
else
returnstr = str;
return returnstr;
}
public static void main(String[] args) {
System.out.println(sql_inj("admin;"));
}
}
jsp中调用该函数检查是否包函非法字符
<%
if(request.getParameter("userID") != null)
userID = request.getParameter("userID").trim();
if (StringUtil.sql_inj(userID) || StringUtil.sql_inj(pwd)){
%>
<Script Language=javascript>alert('参数中包含非法字符!');history.back(-1);</Script>" ;
<%
}else{
……
}%>
StringUtil 是我的通用防注入函数的包名,该函数参考了ASP通用防SQL注入函数,做了一些修改。