如何从hashmap检查用户名和密码

zkure5ic  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(507)

我正在尝试创建一个需要登录的小型客户机/服务器聊天应用程序。我已经做了3个散列Map,一个用于现有用户,一个用于管理,一个用于注册用户。我可以使用预先存在的用户登录,也可以使用管理员用户登录,但无法使用已注册用户的详细信息登录。我怎么能解决这个问题,因为我已经尝试了一些方法,但似乎没有工作?
注册的用户进入一个hashmap,这个hashmap位于一个公共可访问的类中,我可以向该hashmap添加新用户,但是我无法获得log按钮来检查该hashmap。
包含Map的类

public class map {

        public static HashMap<String, String> usermap = new HashMap<>();

        public HashMap<String, String> getUsers()
        {
            return usermap;
        }
     }

登录按钮

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        String username = userText.getText();
        String password = passwordText.getText();
        Component frame = null;

      //Create a map for users where put username as key and password as value
      Map<String, String> usersMap = new HashMap<>();
      usersMap.put("user1", "password1");
      usersMap.put("user2", "password2");

      //Create a map for the admin where put username as key and password as value
      Map<String, String> adminMap = new HashMap<>();
      adminMap.put("Admin", "password");

      // Implement your authentication
      if(usersMap.get(username) != null){
           JOptionPane.showMessageDialog(frame, "You are successfully logged in!");
           setVisible(false); //you can't see me!
           dispose(); //Destroy the JFrame object
           chatClient second = new chatClient();
           second.setVisible(true); //displays the client page

      } else if (adminMap.get(username) != null){
            JOptionPane.showMessageDialog(frame, "You are successfully logged in!");
            setVisible(false); //you can't see me!
            dispose(); //Destroy the JFrame object
            chatServer third = new chatServer();
            third.setVisible(true); //displays the server page

      } else if (map.usermap.equals(username,password)){
            JOptionPane.showMessageDialog(frame, "You are successfully logged in!");
            setVisible(false); //you can't see me!
            dispose(); //Destroy the JFrame object
            chatServer third = new chatServer();
            third.setVisible(true); //displays the server page    
      }else {
            success.setText("Invalid username or password entered");
      }    

    }
c6ubokkw

c6ubokkw1#

正如在评论中所讨论的,一个更清晰的问题建模方法是:

enum UserType {
    EXISTING, ADMIN, REGISTERING;
}

class User {
    private String username;
    private String password;
    private UserType type;
}

实际上,让一个Map按用户名查找密码的唯一原因是,如果您将有很多用户,或者每秒要查找很多次。如果你想要那张Map,那么它看起来像:

Map<String,User> userMap;

你的代码会变成:

if (userMap.contains(username) && userMap.get(username).getPassword().equals(password)) {
    ...
}

相关问题