如果阻止没有正确执行

时间:2018-06-09 18:56:03

标签: java mysql jsp servlets

我有一个java web项目,我有一个方法可以在用户登录时验证用户。我已经设置了密码加密服务,以验证,而不是他的密码是否合法。

    String email = request.getParameter("email");
    String password = request.getParameter("password");


    try {
        byte[] salt = LogicFacade.getSalt(email);

        byte[] attemptedPassword = LogicFacade.getEncryptedPassword(email);

        if (LogicFacade.authenticate(password, attempted password, salt))
//Here salt is null, whenever I try to log in, with a wrong username or password
 {
            User user = null;
            user = LogicFacade.login(email, password);
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setAttribute("role", user.getRole());
            return user.getRole() + "page";
        } else {
            String errorMessage = "the username or password you have selected does not exist";
            throw new LoginSampleException(errorMessage);
        }

    } catch (NoSuchAlgorithmException | InvalidKeySpecException | LoginSampleException ex ) {
        String errorMessage = "We have an internal problem, but we are working as hard as possible, to solve it.";
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        throw new LoginSampleException(errorMessage);
    }
}

}

每当我输入错误的用户名或密码时,它表示Salt-parameter必须为非null。

这是因为我有一个方法从SQL数据库中检索用户的salt,然后返回null。

这是我的身份验证方法:

  public boolean authenticate(String attemptedPassword, byte[] encryptedPassword, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, LoginSampleException {
        // Encrypt the clear-text password using the same salt that was used to
        // encrypt the original password
        byte[] encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);

        // Authentication succeeds if encrypted password that the user entered
        // is equal to the stored hash
        return Arrays.equals(encryptedPassword, encryptedAttemptedPassword);
    }

我的问题是为什么在不满足if条件后它不执行else块。每当我调试项目时,在我尝试深入研究方法后它会直接进入线程类?

是否有可能进入else块并且不会立即抛出NullPointerException?

2 个答案:

答案 0 :(得分:1)

将您的if条件更改为,

if (salt!=null && LogicFacade.authenticate(password, attempted password, salt)){
...if-block
} else {
...else-block
}

由于salt null表示数据库中不存在电子邮件。

答案 1 :(得分:0)

这是因为你的if块在try块内部,当抛出异常时,控件转移到catch块然后程序退出

要纠正这个错误,您可以查看

if(salt==null)

希望它有所帮助!