Java防止SQL注入的几个途径
java防sql注入,最简单的办法是杜绝sql拼接,sql注入攻击能得逞是因为在原有sql语句中加入了新的逻辑,如果使用preparedstatement来代替statement来执行sql语句,其后只是输入参数,sql注入攻击手段将无效,这是因为preparedstatement不允许在不同的插入时间改变查询的逻辑结构 ,大部分的sql注入已经挡住了, 在web层我们可以过滤用户的输入来防止sql注入比如用filter来过滤全局的表单参数
01 import java.io.ioexception;
02 import java.util.iterator;
03 import javax.servlet.filter;
04 import javax.servlet.filterchain;
05 import javax.servlet.filterconfig;
06 import javax.servlet.servletexception;
07 import javax.servlet.servletrequest;
08 import javax.servlet.servletresponse;
09 import javax.servlet.http.httpservletrequest;
10 import javax.servlet.http.httpservletresponse;
11 /**
12 * 通过filter过滤器来防sql注入攻击
13 *
14 */
15 public class sqlfilter implements filter {
16 private string inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,";
17 protected filterconfig filterconfig = null;
18 /**
19 * should a character encoding specified by the client be ignored?
20 */
21 protected boolean ignore = true;
22 public void init(filterconfig config) throws servletexception {
23 this.filterconfig = config;
24 this.inj_str = filterconfig.getinitparameter("keywords");
25 }
26 public void dofilter(servletrequest request, servletresponse response,
27 filterchain chain) throws ioexception, servletexception {
28 httpservletrequest req = (httpservletrequest)request;
29 httpservletresponse res = (httpservletresponse)response;
30 iterator values = req.getparametermap().values().iterator();//获取所有的表单参数
31 while(values.hasnext()){
32 string[] value = (string[])values.next();
33 for(int i = 0;i < value.length;i++){
34 if(sql_inj(value[i])){
35 //todo这里发现sql注入代码的业务逻辑代码
36 return;
37 }
38 }
39 }
40 chain.dofilter(request, response);
41 }
42 public boolean sql_inj(string str)
43 {
44 string[] inj_stra=inj_str.split("\\|");
45 for (int i=0 ; i < inj_stra.length ; i++ )
46 {
47 if (str.indexof(" "+inj_stra[i]+" ")>=0)
48 {
49 return true;
50 }
51 }
52 return false;
53 }
54 }
也可以单独在需要防范sql注入的javabean的字段上过滤:
1 /**
2 * 防止sql注入
3 *
4 * @param sql
5 * @return
6 */
7 public static string transactsqlinjection(string sql) {
8 return sql.replaceall(".*([';]+|(--)+).*", " ");
9 }