为什JSP中使用statement会有SQL 注入漏洞?

来源:百度知道 编辑:UC知道 时间:2024/05/26 00:27:40
当知道用户名,密码填上'xxxx' or 'x'='x'
这是可以跳过检测,就是著名的SQL注入漏洞,但为什么这样可以跳过检测呢?

因为你运行的SQL语句类似于

select * from user where username='' and password = '';

用户名已知user
这样如果密码添上 xxxx' or 'x'='x

就变成了
select * from user where username='user' and password = 'xxxx' or 'x'='x';

而'x'='x'为恒等式,所以password = 'xxxx' or 'x'='x';
永远为真

所以可以通过
所以可以跳过检测

用PreparedStatement可以避免该问题
PreparedStatement ps = connection.prepareStatement("select * from user where password=? and username=?")
ps.setString(1,"username");
ps.setString(2,"password");

这样就不怕单引号破坏sql语句了,也会避免注入问题,同时效率比Statement好,因为Statement到数据库服务器后需要解析,而PreparedStatement 则不需要,节省了时间,特别是对于大量的数据库操作尤为明显