天天看點

Java防SQL注入工具類

import javax.servlet.http.HttpServletRequest;

/**
 * 防SQL注入工具類
 * 把SQL關鍵字替換為空字元串
 * @author zhao
 * @since 2015.7.23
 */
public class AntiSqlInjection {
	
	public final static String regex = "'|%|--|and|or|not|use|insert|delete|update|select|count|group|union" +
						"|create|drop|truncate|alter|grant|execute|exec|xp_cmdshell|call|declare|source|sql";

	/**
	 * 把SQL關鍵字替換為空字元串
	 * @param param
	 * @return
	 */
	public static String filter(String param){
		if(param == null){
			return param;
		}
		return param.replaceAll("(?i)"+regex, "");	//(?i)不區分大小寫替換
	}
	
	/**
	 * 傳回經過防注入處理的字元串
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getParameter(HttpServletRequest request, String name){
		return AntiSqlInjection.filter(request.getParameter(name));
	}
	
	public static void main(String[] args) {
		//System.out.println(StringEscapeUtils.escapeSql("1' or '1' = '1; drop table test")); //1'' or ''1'' = ''1; drop table test
		String str = "sElect * from test where id = 1 And name != 'sql' ";
		String outStr = "";
		for(int i=0; i<1000; i++){
			outStr = AntiSqlInjection.filter(str);
		}
		System.out.println(outStr);
	}
}
           

參考:

java類過濾器,防止頁面SQL注入

http://www.oschina.net/code/snippet_811941_14131

Java防止SQL注入的幾個途徑

http://helloklzs.iteye.com/blog/1329578