简体   繁体   English

将用户名/密码从一个类和方法传递到另一个类

[英]Passing username/password from a class and method to another class

I have to classes, and I need to input two values into one of the classes in my program. 我必须要上课,并且需要在程序中的一个类中输入两个值。

import java.io.IOException;
import java.sql.*;
import static java.lang.System.out;

public class login{

    private String username;
    private String password;

    public void logon() throws IOException {

        System.out.println("Write your Name");
        username = System.console().readLine();
        System.out.println(username);
        System.out.println("Write your Password");
        password = System.console().readLine();
        System.out.println(password);

        try {
            // Does stuff
        }
        catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

Mainly after username and password have been verified in the try catch. 主要是在尝试捕获中验证了用户名和密码之后。 I need to transfer those two strings to another class. 我需要将这两个字符串转移到另一个类。 Seen Below. 见下文。

    public class ClientHandler {
    protected Socket client;
    protected PrintWriter out;
    protected String Username;
    protected String Password;

    public ClientHandler(Socket client) {
       //Does Stuff
    }
}

I would like some pointers to how I can achieve this, either through constructors, or any other method that would be efficient. 我想要一些如何通过构造函数或任何其他有效方法来实现此目标的指针。

I need to transfer those two strings to another class. 我需要将这两个字符串转移到另一个类。

You can do this by creating a setter method (or more than one). 您可以通过创建一个setter方法(或多个)来实现。

You need to add these two methods to your ClientHandler class. 您需要将这两个方法添加到ClientHandler类中。

public void setPassword(String password) {
    this.Password = password;
}

public void setUsername(String username) {
    this.Username = username;
}

Then, you set username and password variables by using these setter method 然后,您可以使用以下setter方法设置用户名和密码变量

ClientHandler handler = ... //Create this object somehow

handler.setUsername(username);
handler.setPassword(password);

In your case this should go in you 'try' block 就您而言,这应该放在您的“尝试”块中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM