下面是MyBatis一个Dao配置

    <select id="findRank" parameterType ="String" resultType="String">
        SELECT u.name FROM UserInfo u
            where 1=1
            and u.UserID=#{userID} ;    
    </select>

打印出执行的SQL语句


 SELECT u.name FROM UserInfo u where 1=1 and u.UserID=?     

这是因为MyBatis启用了预编译功能,在SQL执行前,会先将上面的SQL发送给数据库进行编译;执行时,直接使用编译好的SQL,替换占位符“?”就可以了。因为SQL注入只能对编译过程起作用,所以这样的方式就很好地避免了SQL注入的问题。
【底层实现原理】
MyBatis是如何做到SQL预编译的呢?其实在框架底层,是JDBC中的PreparedStatement类在起作用,PreparedStatement是我们很熟悉的Statement的子类,它的对象包含了编译好的SQL语句。这种“准备好”的方式不仅能提高安全性,而且在多次执行同一个SQL时,能够提高效率。原因是SQL已编译好,再次执行时无需再编译。

话说回来,是否我们使用MyBatis就一定可以防止SQL注入呢?当然不是,请看下面的代码:

    <select id="findRank" parameterType ="String" resultType="String">
        SELECT u.name FROM UserInfo u
            where 1=1
            and u.UserID=${userID} ;   
    </select>

假设userID=1,将SQL打印出来是这样的:

 SELECT u.name FROM UserInfo u where 1=1 and u.UserID=1

假如:
userID=1;drop table UserInfo ;那么sql是这样的

 SELECT u.name FROM UserInfo u where 1=1 and u.UserID=1;drop table UserInfo ;
 测试结果

 SELECT u.name FROM UserInfo u  where 1=1   and u.UserID=1;drop table UserInfo;
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'drop table UserInfo' at line 3
直接报异常,你应该庆幸mybaties做了处理,但是不管怎么说${xxx}是无法阻止SQL注入的。

${xxx}”
缺点: 直接参与SQL编译,不能避免注入攻击。
优点:及到动态表名和列名时,只能使用“${xxx}”这样的参数格式
注意: 这样的参数需要我们在代码中手工进行处理来防止注入。

“#{xxx}“
相当于JDBC中的PreparedStatement
${}:是输出变量的值
优点:#{}是经过预编译的,是安全的;

posted on 2018-04-17 20:14  2637282556  阅读(104)  评论(0编辑  收藏  举报