一、接口方法:
public interface PlayerDao {
List<Player> findByName(@Param("playName") String playName);
}
Mapper文件1:
<select id="findByName" resultType="Player">
select *
from tb_player
where playName = #{playName}
</select>
Mapper文件2:
<select id="findByName" resultType="Player">
select *
from tb_player
where playName = '${playName}'
</select>
二、测试代码
关键代码如下:
public void testSqlInject() {
// 1.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 2.获取对应mapper
PlayerDao mapper = sqlSession.getMapper(PlayerDao.class);
String playName = "Lebron James";
String fakeName = "Lebron Jamesxxx' or '1 = 1 ";
//List<Player> list = mapper.findByName(playName);
List<Player> list = mapper.findByName(fakeName);
for (Player player: list) {
System.out.println(player);
}
System.out.println(list.size());
}
三、验证
验证#操作符
- 使用Mapper文件1:
- 执行testSqlInject,分别放开执行下面2行代码
List<Player> list = mapper.findByName(playName);
List<Player> list = mapper.findByName(fakeName);
执行第一行,只能找到一条记录,
执行第二行,不能找出任何记录,
从而验证了#的防sql注入。
验证$操作符
- 使用Mapper文件2
- 执行testSqlInject,分别放开执行下面2行代码
List<Player> list = mapper.findByName(playName);
List<Player> list = mapper.findByName(fakeName);
执行第一行,只能找到一条记录,
执行第二行,可以找出数据库的全部记录,
从而验证了$的sql注入的不安全性。
四、参考