Java getText() 与 getPassword()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9798066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:44:43  来源:igfitidea点击:

getText() vs getPassword()

javaswingpasswordsjpasswordfield

提问by Nathan Kreider

I'm currently designing a login system for a make-believe company, right now all I have is the Main login, which needs a lot of cleaning up. Below is my login handler.

我目前正在为一家虚构的公司设计登录系统,现在我只有主登录,需要大量清理。下面是我的登录处理程序。

private class LoginButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        if(_uid.getText().equalsIgnoreCase("Nathan") && _pwd.getText().equals("password")) {
            JOptionPane.showMessageDialog(null, "Congratulations on logging in!");
        } else {
          JOptionPane.showMessageDialog(null, "Error on login!");
        }
    }
}

As is, this works perfectly fine, but when I change it to

按原样,这工作得很好,但是当我将其更改为

_pwd.getPassword.equals("password")

it directs straight to the else statement when everything is input correctly. What is wrong here? Full program below.

当一切输入正确时,它直接指向 else 语句。这里有什么问题?完整程序如下。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {
    private static final int HEIGHT = 90;
    private static final int WIDTH = 400;

    JTextField _uid = new JTextField(10);
    JPasswordField _pwd = new JPasswordField(10);
    JButton _login = new JButton("Login");
    JButton _reset = new JButton("Reset");

    public Main() {
       super("Login - Durptech");
        Container pane = getContentPane();
        setLayout(new FlowLayout());

        add(new JLabel("User ID:"));
            add(_uid);
        add(new JLabel("Password:"));
            add(_pwd);

            add(_login);
                _login.addActionListener(new LoginButtonHandler());
            add(_reset);
                _reset.addActionListener(new ResetButtonHandler());

        /*if(_uid.getText().equals("") && _pwd.getText().equals("")) {
            _login.setEnabled(false);
        } else {
            _login.setEnabled(true);
        }*/

       setSize(WIDTH, HEIGHT);
       setResizable(false);
       setLocation(500, 300);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       setVisible(true);
    }

    private class ResetButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            _uid.setText("");
            _pwd.setText("");
            _uid.requestFocusInWindow();
        }
    }

    private class LoginButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if(_uid.getText().equalsIgnoreCase("Nathan") && _pwd.getText().equals("password")) {
                JOptionPane.showMessageDialog(null, "Congratulations on logging in!");
            } else {
              JOptionPane.showMessageDialog(null, "Error on login!");
            }
        }
    }

    public static void main(String[] args) {
        new Main();
    }
}

采纳答案by user207421

password.getPassword()returns a char[], and char[]'s aren't equal to Strings. So you need to compare it to a char[]:

password.getPassword()返回一个 char[],而 char[] 不等于字符串。因此,您需要将其与 char[] 进行比较:

if (Arrays.equals(password.getPassword(), new char[]{'p','a','s','s','w','o','r','d'}))

回答by Hovercraft Full Of Eels

You will want to get to know the API well, to make it your best friend. The key to solving this is to see what JPasswordField#getPassword()returns. Hint 1: it's not a String. Hint 2: you may want to solve this using the java.util.Arrays class methods.

你会想要很好地了解 API,让它成为你最好的朋友。解决这个问题的关键是看看有什么JPasswordField#getPassword()回报。提示 1:它不是字符串。提示 2:您可能想使用 java.util.Arrays 类方法来解决这个问题。

The reason getPassword doesn't return a String is because of the way Java handles Strings -- it can store them in the String pool, allowing Strings to hang out in the program longer than you'd expect, and making the Strings potentially retrievable by malware -- something you don't want to have happen to a password. It's much safer to work with char arrays.

getPassword 不返回字符串的原因是因为 Java 处理字符串的方式——它可以将它们存储在字符串池中,允许字符串在程序中停留的时间比您预期的要长,并使字符串可能被检索恶意软件——您不希望密码发生这种情况。使用字符数组更安全。

Incidentally, don't use JPasswords deprecated getText()method or change a char array to a String using the new String(char[])constructor since as these both return a String, they are not secure.

顺便说一句,不要使用 JPasswords 不推荐使用的getText()方法或使用new String(char[])构造函数将字符数组更改为字符串,因为它们都返回字符串,因此它们不安全。

回答by black panda

JPasswordField.getPassword()returns a char []instead of a String. This is done for the sake of security. You should compare the characters inside the array instead of seeing if the char [] .equals(a String);

JPasswordField.getPassword()返回 achar []而不是 a String。这样做是为了安全起见。您应该比较数组中的字符,而不是查看 char [] .equals(a String);

回答by user207421

As all the other answers have said, JPasswordField returns a char[] when you call the getPassword() method. However, the way I have it set in my sample log on form is I have a method for validating the input. I have two arrays for storing usernames[] and passwords[] and then I have my username input, and my password input. The password input in my method changes the char[] to a string before continuing, you can do so like this:

正如所有其他答案所说,当您调用 getPassword() 方法时, JPasswordField 返回一个 char[] 。但是,我在示例登录表单中设置它的方式是我有一种验证输入的方法。我有两个用于存储用户名 [] 和密码 [] 的数组,然后我输入了用户名和密码。在我的方法中输入的密码在继续之前将 char[] 更改为字符串,您可以这样做:

 String PasswordTyped = new String(_pwd.getPassword());

Then take that string and place that in your 'if' statement:

然后取出该字符串并将其放在您的“if”语句中:

 if (_uid.equals("Nathan") && PasswordTyped.equals("password") {
     JOptionPane.showMessageDialog(null, "Congrats, you logged in as Nathan");
 }

However, as I mentioned my validation method runs on the two arrays of usernames[] and passwords[], while accepting a string and a char[] as input. I will copy and paste my method so you can implicate it if you would like:

然而,正如我提到的,我的验证方法在用户名 [] 和密码 [] 的两个数组上运行,同时接受一个字符串和一个字符 [] 作为输入。我将复制并粘贴我的方法,以便您可以根据需要将其包含在内:

public static void validate(String u, Char[] pass) {
    String password = new String(pass);
    boolean uGood = false;
    String[] usernames = new String[2];
    String[] passwords = new String[usernames.length];

    usernames[0] = "Don";
    passwords[0] = "password";
    usernames[1] = "Jared";
    passwords[1] = "password";


    for (int i = 0; i < usernames.length; i++) {

        if (usernames[i].equals(u) && passwords[i].equals(password)) {
            uGood = true;
        }
    }
    if (uGood) {
        System.out.println("Hooray, you did it!");
    }
    else {
        JOptionPane.showMessageDialog(null, "Incorrect Username\nand/or Password.");
    }
}

Finally, you would call this validation method by typing:

最后,您可以通过键入以下内容来调用此验证方法:

validate(_uid.getText(), _pwd.getPassword());