Atif
Atif

Reputation: 226

Unable to get required JDBC Exception

I have created a login form using java servlets and jsp's. The login information such as username and password is saved in Database. My question is that when a user enters the information that my java class fails to find in database I dont get the exception. How could I create an exception if the login data isnt available in Db?

public boolean loginValidator(String e, String p) throws SQLException {

    String userName = e;
    String password = p;
    boolean validate = false;
    try{
    PreparedStatement ps = connection.prepareStatement("SELECT * FROM user WHERE email = ? and password = ?");
    ps.setString(1, userName);
    ps.setString(2, password);

    ResultSet rst = ps.executeQuery();

    while (rst.next()) {
        validate = (rst.getString("email").equals(userName)) && ((rst.getString("password").equals(password)));
    }}
    catch(SQLException ex){
        System.out.println(ex.getMessage());
        validate = false;
    }


return validate;
}

This is actually a method in my java class that validates and send boolean type to a servlet and later servlet decides to direct or restrict the access to application subject to the boolean type returned.

PS: A new learner of javaWeb.

Upvotes: 0

Views: 111

Answers (1)

Jozef Chocholacek
Jozef Chocholacek

Reputation: 2924

And a learner of SQL, right? Because there is NO exception, if there is no such line in the DB table. The query just returns empty ResultSet. So you have to check, whether the result set is empty or not (and then alternatively check the email and password - but that is IMHO superfluous).

public boolean loginValidator(String userName, String password) {
    try{
        PreparedStatement ps = connection.prepareStatement("SELECT * FROM user WHERE email = ? and password = ?");
        ps.setString(1, userName);
        ps.setString(2, password);
        ResultSet rst = ps.executeQuery();
        return rst.next(); // whether DB contains such record
    } catch(SQLException ex){
        ex.printStackTrace(); // TIP: use logging
    }
    return false;
}

Btw. I would strongly recommend you NOT to store plaintext passwords in the DB.

Upvotes: 1

Related Questions