针对PostgreSQL使用JDBC验证凭据



所以我一直在尝试在登录服务器时验证我的凭据。这是我试图验证的一组简单数据。

(456789,"Dave123","密码","Dave","Davidson","dave@dadavid’,2(,(123456,'John456','123456','John','Johnson','john@jojohn’,1(,(456878,Kate789,abcdef,Kate,Katesonkate@kitkat’,1(

public class LoginService {
//username and password with id identifier
//0 for false, 1 for employee and 2 for manager
public boolean login(String username, String password, int id) {



try(Connection connection = ConnectionUtil.getConnection()) {

ResultSet resultSet = null; // intialize an empty resultset that will store the results of our query.
//sql statement to get all of the info from reimbursement
String sql = "select * from users where username =? and pass=? and user_role_id=?"
+ "values (?,?,?)";


PreparedStatement preparedStatement = connection.prepareStatement(sql); 

preparedStatement.setString(2, username );
preparedStatement.setString(3, password );
preparedStatement.setInt(7, id);

if(username.equals(username) && password.equals(password) && id == (1) ) {
return true;
}
if(username.equals(username) && password.equals(password) && id == (2) ) {
return true;
}

}catch (Exception e) {
// TODO: handle exception
}
return false;
}
}

因此,当它完成验证时,如果用户名和密码在数据库中,它将返回true。否则,它会返回一个false,不让用户登录。但目前,它所做的只是返回false,不允许用户登录。

我试着在邮递员上运行这个,它会接受这些值并允许我登录,但在实时服务器上尝试会拒绝它

<input id="username" type="text" placeholder="username" class="col-sm-4 form-control">
<input id="password" type="password" placeholder="password" class="col-sm-4 form-control"> 
<input id="id" type="number" placeholder ="id" class="col-sm-4 formcontrol">

这是我的html中的内容。

您的SQL查询一开始就是错误的。但更重要的是,您甚至没有运行该查询,也没有处理查询的结果。

select语句的values子句无效。所以移除它。

String sql = "select * from users where username =? and pass=? and user_role_id=?";

你只有三个参数,所以你需要用数字1,2和3(而不是2,3,7(来传递它们

preparedStatement.setString(1, username );
preparedStatement.setString(2, password );
preparedStatement.setInt(3, id);

然后,您必须使用execute()来实际运行查询并接收结果:

ResultSet rs = preparedStatement.execute();

在调用next()之后,返回的值将从ResultSet中检索,而不是从语句中检索,例如:

if (rs.next()) {
String nameFromDb = rs.getString("username");
String pwdFromDb = rs.getString("password");
int id = rs.getInt("id");
}

但是,由于这三个参数都是WHERE子句的一部分,因此您永远不会得到值与输入不同的结果。因此,您只需要检查查询是否返回了一行:

if (rs.next()) {
return true;
}

不过,您需要在返回之前关闭preparedStatement(),以避免数据库中的资源泄漏。

最新更新