java - 如何创建一个java程序让用户使用密码登录并存储数据

标签 java user-interface authentication

我正在尝试制作一个简单的java密码管理器(我不担心我现在如何存储密码,因为我只是想首先让整体结构正确)。我陷入了如何允许用户登录的困境。我有一个存储用户名和密码的文件 - 因此,我首先使用扫描仪从未经身份验证的用户获取输入,然后对照文本文件检查它是否与帐户匹配。如果用户输入与用户名和密码匹配,我怎样才能让该用户访问他的 User 对象?我遇到的问题是这个用户对象已经创建(创建帐户时),但是我如何让用户登录并访问用户类中的所有方法,即changeUserPassword或getPassword?

我已经考虑过使用不同的设计模式,例如观察者,但我认为这些模式不适合我想要做的事情。

我想知道是否有人知道我可以遵循的设计模式或知道可以让我访问已创建的用户类之外的对象(用户)的实现(即已经创建帐户)并且对其进行更改。

public void login() throws IOException {
    // use a scanner to get login details
    Scanner s = new Scanner(System.in);

    System.out.print("email: ");
    String email = s.next();

    System.out.print("password: ");
    String password = s.next();

    String check = email + ", " + password;

    // loop through file and check if we find a matching email and password
    File f = new File("member.txt");
    Scanner sc = new Scanner(f);

    while (sc.hasNext()) {
        if (sc.nextLine().equals(check)) {
            System.out.println("Logging in...");
            // how do i now access the user object that matches the username and password that were given?
        }
    }
}

最佳答案

这不是您与数据库交互的方式。编写一个User类来存储用户名和密码。然后编写一个数据库类来读取文本文件并创建 User 对象的 ArrayList。然后使用 User.name 进行搜索,并在登录前检查 User.password 进行验证。

数据库会将数据从文本文件“加载”到 ArrayList 中,这将是您的程序将与之交互的内容。如果您想重写文本文件,请编写一个保存函数来清除并打印到相关文件。

这是一个数据库类的示例(来 self 的一个旧项目),它以以下格式读取学生的数据: 姓名:HARSH|PID:12|专业:null|次要:null|CGPA:4.100000|学院:null|电子邮件:abcd@gmail.com

import java.util.*;
import java.text.*;
import java.time.*;
import java.io.*;

public class Database{
    public List<Student> studentList;
    private long lastModified;
    @SuppressWarnings("unchecked")

    public Object loadDb()
    {//Loads the database from file.
        File data = new File("database.db");
        if(lastModified == data.lastModified())
        {
            return studentList;//Returning main memory;
        }
        Scanner sc;
        try
        {
            sc = new Scanner(data).useDelimiter("\n");//To get individual lines.
            String line;
            if(studentList!=null)
            {//Clearing main memory.
                studentList.clear();
            }
            else
            {//Creating new main memory.
                studentList = new ArrayList<Student>();
            }

            while(sc.hasNext())
            {
                line = sc.next();
                Scanner l = new Scanner(line).useDelimiter("\\|");//To get info
                String name, PID, major, minor, cgpaSt, college, email;
                name = l.next().split(":")[1];
                PID = l.next().split(":")[1];
                major = l.next().split(":")[1];
                minor = l.next().split(":")[1];
                cgpaSt = l.next().split(":")[1];
                college = l.next().split(":")[1];
                email = l.next().split(":")[1];
                double CGPA = Double.valueOf(cgpaSt);
                Student stud = new Student(name,PID, major, minor, CGPA, college, email);//Creating new student with same info.
                studentList.add(stud);//Adding the student to memory.
            }
            sc.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }   
        return studentList;
    }
    @SuppressWarnings("unchecked")
    public void updateDb(Object studList)
    {//Updates the database.
        File data = new File("database.db");
        PrintWriter fs;
        try
        {
            fs = new PrintWriter(data);
        }
        catch(IOException e)
        {
            System.out.println("IO Exception!");
            return;
        }
        fs.flush();
        ArrayList<Student>studs = (ArrayList<Student>)studList;
        for(int i = 0;i<studs.size();i++)
        {
            fs.print(studs.get(i).toString());
            if(i != studs.size() -1)
            {
                fs.print("\n");
            }
        }
        fs.close();
        lastModified = data.lastModified();
        loadDb();//Loading updated database.
    }


}

您必须为您的用户类编写一个 toString() 函数,并根据您的格式修改读数。这将允许您在中心类中创建一个变量Database userData = new Database();。然后,您可以与studentList(在您的例子中为userList)交互,并搜索该用户,然后检查他们的密码是否正确。

关于java - 如何创建一个java程序让用户使用密码登录并存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57739105/

相关文章:

python - 如何从 Java 客户端向 Python FastAPI 服务器发出 JSON POST 请求?

JavaFX 表格 View 清除集合

java - 如何使 JMenu 项在单击时执行某些操作

angular - 用户离线时如何使用 Angular PWA 处理身份验证?

json - 使用 Rails 3 应用程序的 ios json 身份验证

ruby-on-rails - 测试 Rails API 以使用 devise 进行注册。错误 : "Missing ' confirm_success_url' parameter.“

java - 在 Java 中根据用户输入绘制空心星号正方形/矩形

java - 如果 Spring Batch 中事务失败,如何停止 JpaItemWriter?

如果不使用大括号和 if,Java 代码编译错误

user-interface - Scala、动画和图形用户界面