比如说我的DaoImp是这样写的
package com.xatu.dao.imp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.xatu.dao.UserDao;
import com.xatu.domain.User;
import com.xatu.utils.JDBC;
public class UserDaoImp implements UserDao {
private Connection conn;
@Override
public User userLogin(String username,String password){
JDBC jdbc = new JDBC();
User u = null;
try {
conn = jdbc.getConn();
Statement createStatement = conn.createStatement();
ResultSet set = createStatement.executeQuery("select * from usertab where username = '" + username +
"' and password = " + "'" + password + "'");
while(set.next()) {
u = new User();
u.setUsername(set.getString(1));
u.setPasswordString(set.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return u;
}
}
ResultSet set = createStatement.executeQuery(“select * from usertab where username = '” + username +
"’ and password = " + “’” + password + “’”);
注意这个sql查询语句 这个会导致我们收到SQL注入攻击!
如何攻击?
很简单
“select * from usertab where username = '” + username +
"’ and password = " + “’” + password + “’”
因为我们拿的是这个sql语句去做业务的,username和password是用户可以输入的参数 只要在password处加入一些可以直接影响结果的语句就可以了
如何影响结果?
比如 在密码输入框内加 or ‘1’=‘1’ 这样的字样 因为1绝对等于1,所以针对那条查询语句会直接让你成功进入数据库
如何避免
使用预处理sql语句的方式即可,因为预处理机制是把用户的输入完整的当作参数处理了。
PreparedStatement statement = conn.prepareStatement
("select * from usertab where username = ? AND password = ?");
statement.setString(1, username);
statement.setString(2, password);