如何在Java-mysql中验证用户名和密码?

时间:2013-02-21 06:25:22

标签: java passwords

如何以最正确的方式验证用户输入数据库的用户名和密码?

In c++, we used to verify by using if-else:
    if((user == "username")&&(pass == "password")){
             cout<<"You are now logon!";
    }

在java-mysql中我不确定我是否走在正确的轨道上:

登录按钮

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        user = jTextField1.getText();
        pass = jPasswordField1.getPassword();
        login();
}

方法/功能

private void login() {

        try {
                if (user != null) {
                sql = "Select * from users_table Where username='" + user + "'";
                rs = stmt.executeQuery(sql);

                rs.next();
                username = rs.getString("username");
                password = rs.getString("password");

            }
        } 
    catch (SQLException err) {
            JOptionPane.showMessageDialog(this, err.getMessage());
        }

}

如果用户输入的用户名和密码与数据库中的用户名和密码匹配,那么他将被定向到新的jFrame else 消息对话框将弹出说无效的用户名或密码。有人可以帮助我使用我的代码,我不知道如何使用带有mysql的if-else语句;

谢谢! :)

5 个答案:

答案 0 :(得分:3)

  • 始终将哈希加密密码存储在数据库中,有关加密密码的详细信息,请参阅JASYPT
  • 加密用户输入的密码并比较两个加密密码
  • 查询数据库时使用parametrized queries

答案 1 :(得分:2)

实施以下代码:

private void login() {
    try {
        if (user != null && pass != null) {
            String sql = "Select * from users_table Where username='" + user + "' and password='" + pass + "'";
            rs = stmt.executeQuery(sql);
            if (rs.next()) {
                //in this case enter when at least one result comes it means user is valid
            } else {
                //in this case enter when  result size is zero  it means user is invalid
            }
        }

        // You can also validate user by result size if its comes zero user is invalid else user is valid

    } catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }

}

答案 2 :(得分:1)

你不再需要对mySQL做任何事了。您已拥有凭据。 一个例子:

if ((user.equals(username)) && (pass.equals(password))) {
   JFrame newFrame = new JFrame();
} else {
   JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE); 
}

答案 3 :(得分:1)

使用预准备语句以及像DButils这样的库,这将大大简化您的工作。

此外,请勿使用select name from members where code =?等替换传递参数。如果您有许多参数,请创建一个对象数组并将其传递到对象数组中,例如Objects[] parms = {code1,code2}

答案 4 :(得分:-2)

if (username.length()>0 && password.length()>0)
{
    String query = "Select * from adminlogin Where Username='" + username + "' and Password='" + password + "'";

    rs = sta.executeQuery(query);

   if (rs.next()) 
   {

        home hme=new home();
        this.setVisible(false);
        hme.setVisible(true);
   } 
   else 
   {
       JOptionPane.showMessageDialog(null,"username and password are wrong ");
   }
}
else
{
      JOptionPane.showMessageDialog(null,"please field username and password ");
}