dao.login("wonderq", "root"); 运行usersDAO类,控制台输出结果如下:
?

从输入结果可以看出,使用用户名为“wonderq”,密码为“root”可以登录成功,由于用户名为"wonderq",密码为"root"在数据库中是存在的数据,登陆成功符合预期结果。另外,从输出sql语句来看,最终变量信息替换为实际传入的参数信息了。
步骤四:测试login方法
在UserDAO的main方法中,使用用户名为"chenxin",密码为"a' OR 'b'='b"作为login方法的参数,测试是否能成功登录,代码如下所示:
?
UserDAO dao=new UserDAO();
//dao.login("wonderq", "root");
dao.login("chenxin", "a' OR 'b'='b"); 运行UserDAO类,控制台输出如下结果:
?

从输出结果来看,使用用户名为“chenxin”,密码为"a' OR 'b'='b"可以登录成功,但是用户名为"chenxin",密码为"a' OR 'b'='b"在数据库中是不存在的数据,登录成功不符合预期结果,问题出在哪里呢?
问题出在sql语句上。查看上述控制台输出结果,可以看出SQL语句的where字句中,使用or关键字连接两个表达式,即or关键字后边的表达式如果返回true。而or关键字后面的表达式为" 'b'='b" ,该表达式的返回结果永远为true,因此,where条件的返回结果一定为true。这种现象在编程中成为SQL注入,是应该避免的编程方式。可以使用PreparedStatement来防止SQL注入。
步骤五:使用PreparedStatement实现验证用户名和密码功能
在UserDAO类中更改login方法,在该方法中使用PreparedStatement执行SQL语句,来实现验证用户名密码功能。代码如下所示:
?
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserDAO {
public static void main(String[] args){
UserDAO dao=new UserDAO();
//dao.login("wonderq", "root");
dao.login("chenxin", "a' OR 'b'='b");
}
public void login(String username,String password){
Connection con=null;
PreparedStatement stmt=null;
ResultSet rs=null;
String sql=null;
try {
sql="select * from users where username= ? and password= ?";
System.out.println("执行的sql语句:"+sql);
con=ConnectionSource.getConnection();
stmt=con.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
rs=stmt.executeQuery();
if(rs.next()){
System.out.println("登录成功!");
}else{
System.out.println("登录失败!");
}
} catch (SQLException e) {
System.out.println("数据库访问异常!");
throw new RuntimeException(e);
}
finally{
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e2) {
System.out.println("释放资源发生异常!");
}
}
}
}
?
步骤六:测试login方法
在UserDAO类的main方法中,使用用户名为"chenxin",密码为"a' OR 'b'='b"作为login方法的参数,测试是否能成功登录,代码就是上面的,运行之后,控制台输出结果:

从输出结果来看,登陆失败。用户名为"chenxin",密码为"a' OR 'b'='b"的数据在数据库users表中是不存在的数据,登录失败符合测试的预期,有效的防止了SQL注入的问题。
本节结束~。。下次进入JDBC的高级编程。。
?