Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.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 针对ArrayList的登录身份验证_Java_Model View Controller_Login_Arraylist_Textfield - Fatal编程技术网

Java 针对ArrayList的登录身份验证

Java 针对ArrayList的登录身份验证,java,model-view-controller,login,arraylist,textfield,Java,Model View Controller,Login,Arraylist,Textfield,当我尝试用arraylist验证用户名和密码时,我总是会遇到空指针异常,我不确定是什么原因导致了它。用户将其信息输入用户名和密码jtext字段,并根据用户名和密码的硬编码列表进行检查。也许有人可以提出问题的根源,或者提出一种更合理的解决方法 LoginUI,当按下submitButton时 public class SubmitListener implements ActionListener{ public void actionPerformed(ActionEvent evt){

当我尝试用arraylist验证用户名和密码时,我总是会遇到空指针异常,我不确定是什么原因导致了它。用户将其信息输入用户名和密码jtext字段,并根据用户名和密码的硬编码列表进行检查。也许有人可以提出问题的根源,或者提出一种更合理的解决方法

LoginUI,当按下submitButton时

public class SubmitListener implements ActionListener{
    public void actionPerformed(ActionEvent evt){
        System.out.println("Submit button pressed");
        String usernameToPass = usernameField.getText();
        String passwordToPass = passwordField.getText();
        System.out.println("username and password: "+usernameToPass+" "+passwordToPass);
        if(theLoginCntl.authenticate(usernameToPass, passwordToPass)){      
            LoginUI.this.setVisible(false);
            theLoginCntl.getMainMenuCntl();
        }else{
            System.out.println("Invalid Password!");
        }
    }
}
LoginCntl,身份验证方法

public class LoginCntl {

private UserList theUserList;
private LoginUI theLoginUI;

private ArrayList<String> validUsers;
private ArrayList<String> validPasswords;

public LoginCntl(){
    theLoginUI = new LoginUI(this);
}

public void getMainMenuCntl(){
    MainMenuCntl theMainMenuCntl = new MainMenuCntl();
}


public boolean authenticate(String username, String password){

    validUsers = new ArrayList();
    validUsers = theUserList.getValidUsers();     //code breaks on this line
    System.out.println("validUsers has been initialized");
    validPasswords = new ArrayList();
    validPasswords = theUserList.getValidPasswords();
    for (int i = 0; i < validUsers.size(); i++) {
        if (validUsers.get(i).equals(username) && validPasswords.get(i).equals(password)) {
            return true;
        }
    }
    theLoginUI.passwordField.setText("");
    JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
    return false;

    //return true;

}
公共类LoginCntl{
私有用户列表用户列表;
私人物流;
私人ArrayList validUsers;
私人ArrayList有效密码;
公共后勤{
theLoginUI=新的LoginUI(本);
}
public void getMainMenuCntl(){
MainMenuCntl theMainMenuCntl=新建MainMenuCntl();
}
公共布尔身份验证(字符串用户名、字符串密码){
validUsers=新的ArrayList();
validUsers=theUserList.getValidUsers();//此行的代码中断
System.out.println(“validUsers已初始化”);
validPasswords=新ArrayList();
validPasswords=用户列表。getValidPasswords();
对于(int i=0;i
}

UserList类,硬编码有效的用户名和密码组合

public class UserList {
private ArrayList<String> validUsers;
private ArrayList<String> validPasswords;

public UserList(){
    validUsers = new ArrayList();
    validPasswords = new ArrayList();

    validUsers.add("user1");
    validUsers.add("user2");
    validUsers.add("user3");
    validUsers.add("user4");
    validUsers.add("user5");

    validPasswords.add("password1");
    validPasswords.add("password2");
    validPasswords.add("password3");
    validPasswords.add("password4");
    validPasswords.add("password5");
}

public ArrayList<String> getValidUsers(){
    return validUsers;
}

public ArrayList<String> getValidPasswords(){
    return validPasswords;
}
公共类用户列表{
私人ArrayList validUsers;
私人ArrayList有效密码;
公共用户列表(){
validUsers=新的ArrayList();
validPasswords=新ArrayList();
validUsers.添加(“用户1”);
validUsers.添加(“用户2”);
validUsers.添加(“用户3”);
validUsers.添加(“用户4”);
validUsers.添加(“用户5”);
有效密码。添加(“密码1”);
有效密码。添加(“密码2”);
有效密码。添加(“密码3”);
有效密码。添加(“密码4”);
有效密码。添加(“密码5”);
}
公共阵列列表getValidUsers(){
返回validUsers;
}
公共阵列列表getValidPasswords(){
返回有效密码;
}

}在调用用户列表中的方法之前,需要初始化用户列表。大概是这样的:

validUsers = new ArrayList();    
theUserList= new UserList(); // like this
validUsers = theUserList.getValidUsers();     
System.out.println("validUsers has been initialized");

我建议您使用TreeMap而不是两个ArrayList:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;



public class Main extends JFrame {


    /* ============================ VARIBLES ============================ */

    /** Needed because JFrame implements the Serializable Interface. Forget it*/
    private static final long serialVersionUID = 959648274013445628L;

    /** The button to confirm */
    JButton okButton;

    /** The texfield for the username */
    JTextField usernameField;

    /** The texfield for the password */
    JTextField passwordField;


    /** Store our passwords.  A TreeMap will associate each login with its
     * respective password: no need to use 2 ArrayLists. Also, is much more
     * efficient. */
    private static TreeMap<String, String> passwords = new TreeMap<>();




    /* ======================= PASSWORDS HANDLING ======================= */

    /**
     * This will fill passwords with 'login1'+'password1' ... 'login4'+'password4'
     */
    private void fillPasswords(){

        for(int i=0; i<5; i++)
            passwords.put("login"+i, "password"+i);
    }


    /**
     * Return if a username-password pair is a valid login .
     * 
     * @param username   The username
     * @param password   The password
     * @return   true if is a valid login, false otherwise.
     */
    public boolean authenticate(String username, String password){

        String storedPW = passwords.get(username);

        if(  storedPW == null ||          //<- The TreeMap hasn't any register for 'username'
            !storedPW.equals(password)  ) //<- There are a register for 'username', but it
            return false;                 //    does not match wit the password typed.

        return true;

        //Remember that you can't use the expression:   storedPW = password
        //That expression will be always false, because is comparing String references,
        //not String values.  For that reason, you need to use equals() method.
    }



    /* ========================= OTHER  METHODS ========================= */


    /** 
     * This is a fast, basic UI, modify it as you need.
     */
    private void createUI(){

        setSize(460,175);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setLayout(null);

        usernameField = new JTextField();
        add(usernameField);
        usernameField.setSize(120,30);
        usernameField.setLocation(50,50);

        passwordField = new JTextField();
        add(passwordField);
        passwordField.setSize(120,30);
        passwordField.setLocation(180,50);

        okButton = new JButton("Ok");
        add(okButton);
        okButton.setSize(100,30);
        okButton.setLocation(310,50);
        okButton.addActionListener( new SubmitListener(this) );
    }



    /**
     * Fill the passwords TreeMap and launch the UI
     */
    private Main(){

        fillPasswords();
        createUI();
    }



    public static void main(String[] args){

        new Main();
    }


}





/**
 * This class handles The event of pressing the okButton.
 */
class SubmitListener implements ActionListener{

    Main main;


    SubmitListener(Main main){
        this.main = main;
    }


    @Override
    public void actionPerformed(ActionEvent arg0) {

        String usernameToPass = main.usernameField.getText();
        String passwordToPass = main.passwordField.getText();

        if( main.authenticate(usernameToPass, passwordToPass) )
            JOptionPane.showMessageDialog(main, "Login sucessfull",
                    "Sucess", JOptionPane.DEFAULT_OPTION);

        else
            JOptionPane.showMessageDialog(main, "Password unknow, try again",
                    "Failure", JOptionPane.WARNING_MESSAGE);

        //Add this if you want the 2 textfield to be cleared after a login try:
        main.usernameField.setText("");
        main.passwordField.setText("");
    }

}
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.TreeMap;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JOptionPane;
导入javax.swing.JTextField;
公共类主框架{
/*=================================================================================================================================*/
/**需要,因为JFrame实现了可序列化接口。忘记它吧*/
私有静态最终长serialVersionUID=959648274013445628L;
/**按下确认按钮*/
JButton-okButton;
/**用户名的文本字段*/
JTextField usernameField;
/**密码的文本字段*/
JTextField密码字段;
/**存储我们的密码。树形图会将每个登录名与其密码关联
*各自的密码:不需要使用2个ArrayList。另外,更详细
*效率高*/
私有静态树映射密码=新树映射();
/*==============================================================================================================================*/
/**
*这将使用“login1”+“password1”…“login4”+“password4”填充密码
*/
私有无效密码(){

对于(int i=0;iAdd)整个异常(包括调用堆栈)到您的帖子。您的theUserList可能为空。向我们展示您如何声明/初始化UserList以及堆栈跟踪。
theUserList
在哪里定义以及它如何获取其值?使用完整的NoteCntl类进行更新,其中包括UserList初始化。是的,就是这样。谢谢您的帮助。