Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将文本字段和密码字段与字符串值进行比较?_Java_Mysql_Jdbc_Jtextfield_Jpasswordfield - Fatal编程技术网

Java 如何将文本字段和密码字段与字符串值进行比较?

Java 如何将文本字段和密码字段与字符串值进行比较?,java,mysql,jdbc,jtextfield,jpasswordfield,Java,Mysql,Jdbc,Jtextfield,Jpasswordfield,这是我使用JDBC连接的登录表单的代码。代码没有错误,但当我运行它时,它总是转到else语句 Connection con; Statement st; ResultSet rs; try{ Class.forName("java.sql.Driver"); con=DriverManager.getConnection ("jdbc:mysql://localhost/database","root","password");

这是我使用JDBC连接的登录表单的代码。代码没有错误,但当我运行它时,它总是转到else语句

    Connection con;
    Statement st;
    ResultSet rs;
    try{
      Class.forName("java.sql.Driver");
      con=DriverManager.getConnection   ("jdbc:mysql://localhost/database","root","password");
      st=con.createStatement();
      rs=st.executeQuery("select * from users;");
      while(rs.next()){
                String userID=rs.getString("userID");
                String password=rs.getString("password");

                if(userID.equals(txtuserID.getText())
                    && (password.equals(txtpassword.getPassword())) {
                // ***HERE IS MY PROBLEM I WANT TO CHECK IF WHATS IN THE 
                // TEXT FIELD OR PASSWORD FIELD IS THE SAME FROM MySQL***
                    JOptionPane.showMessageDialog(null,"you have logged in");
                    new MainForm().setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null,"Incorrect username and password");
                }
     }
  } catch(Exception e) {
     JOptionPane.showMessageDialog(null,"Error in Connectivity: " +e.getMessage());
  }  

JPasswordField getPassword()方法返回char[]。比较前转换为字符串:(实际使用这些字符构造一个新字符串…)


关于chenchuk的回答,将字符数组保留为字符数组,而不将其转换为字符串会更安全,因为字符串更容易被盗

因此,不要像chenchuk的回答那样将密码的char[]转换为字符串:

if(userID.equals(txtuserID.getText()) &&
  (password.equals(new String((txtpassword.getPassword()))) {
}
使用
java.util.Arrays.equals(…)
方法更安全:

if(userID.equals(txtuserID.getText()) 
        && Arrays.equals(txtpassword.getPassword(), password.toCharArray())) {

    // your code goes here
}

什么是
txtpassword
?这是非常正确的,但是,如果这是您的问题,您仍然没有正确处理它。看见
if(userID.equals(txtuserID.getText()) 
        && Arrays.equals(txtpassword.getPassword(), password.toCharArray())) {

    // your code goes here
}