如何将文本字段和密码字段与字符串值进行比较?
How can I compare text field and password field to String values?
这是我使用 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() 方法returns char[]。在比较之前转换为 String :(实际上用这些字符构造一个新的 String ...)
if(userID.equals(txtuserID.getText()) &&
(password.equals(new String((txtpassword.getPassword()))) {
}
关于 chenchuk 的回答,将 char 数组保留为 char 数组而不是将它们转换为 String 会更安全,这样更容易被盗。
因此,不要像 chenchuk 的回答那样将密码的 char[] 转换为 String:
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
}
这是我使用 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() 方法returns char[]。在比较之前转换为 String :(实际上用这些字符构造一个新的 String ...)
if(userID.equals(txtuserID.getText()) &&
(password.equals(new String((txtpassword.getPassword()))) {
}
关于 chenchuk 的回答,将 char 数组保留为 char 数组而不是将它们转换为 String 会更安全,这样更容易被盗。
因此,不要像 chenchuk 的回答那样将密码的 char[] 转换为 String:
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
}