简体   繁体   中英

authentication — making username and password global in java

I wanted to authenticate a user. For this I am using mysql connection. The following is the code :

 JTextField txt_Username= new JTextField();
 String Username;
 txt_Username.addFocusListener(new FocusAdapter() {
        @Override
        public  void focusLost(FocusEvent arg0) {
     {
         Username= txt_Username.getText();
     }
 });

Similarly there is code for password. Now I want this username and password outside of its local scope so that clicking on the JButton will fire the sql databse and authenticate with the above username and password.

I am a naive in Java. Could anybody please help in here ?

I have the full code here . Please I need to understand where I am going wrong :

     import java.awt.EventQueue;


 public class Frame{

 private private JFrame frame1;
 private JTextField textFieldUserName;
 private JTextField txtPassword;

 public String textUserValue;


/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Frame window = new Frame();

                window.frame1.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 * @throws SQLException 
 */
public multipleFrame() throws SQLException {
    initialize();
}

/**
 * Initialize the contents of the frame.
 * @throws SQLException 
 */
private void initialize() throws SQLException {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblNewLabel = new JLabel("");
    lblNewLabel.setIcon(new ImageIcon("C:\\sad.jpg"));
    lblNewLabel.setBounds(10, 36, 196, 187);
    frame.getContentPane().add(lblNewLabel);

    JLabel lbl_Password = new JLabel("PASSWORD");
    lbl_Password.setBackground(new Color(128, 128, 128));
    lbl_Password.setOpaque(true);
    lbl_Password.setBounds(217, 140, 75, 14);
    frame.getContentPane().add(lbl_Password);


    final Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/schema","user","pwd");
    final JTextField textFieldUserName = new JTextField();
    textFieldUserName.addFocusListener(new FocusAdapter() {


        @Override
        public  void focusLost(FocusEvent arg0) {
             String textUserValue = textFieldUserName.getText();
             System.out.println(textUserValue+"  hi");
             String textUserValue1 =textUserValue;

        }
    });
    System.out.println(textUserValue+"  HI");

    textFieldUserName.setBounds(324, 79, 108, 20);
    frame.getContentPane().add(textFieldUserName);
    textFieldUserName.setColumns(10);
    System.out.println();

    JLabel label = new JLabel("USERNAME");
    label.setOpaque(true);
    label.setBackground(Color.GRAY);
    label.setBounds(216, 82, 75, 14);
    frame.getContentPane().add(label);

    txtPassword = new JTextField();
    txtPassword.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
             String textPasswordValue = txtPassword.getText();
             System.out.println(textPasswordValue+"  hi");
        }
    });
    txtPassword.setColumns(10);
    txtPassword.setBounds(324, 137, 108, 20);
    frame.getContentPane().add(txtPassword);

    JButton btnLogin = new JButton("LOGIN");
    btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

        }
    });
    btnLogin.setBounds(262, 200, 91, 23);
    frame.getContentPane().add(btnLogin);

    PreparedStatement stmt1 = null;
                try {
                    stmt1 = con.prepareStatement("select username from LOGIN_TABLE where    username='"+textUserValue+"'");
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                ResultSet result1 = null;
                try {
                    result1 = stmt1.executeQuery();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    while (result1.next()) {
                        String user_name_db=result1.getString("username");
                        System.out.println(user_name_db);
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }
 }

Turn your Username variable into public. And place it just inside the class, not in any method.

Example:

public String Username;

Or if you want to retain its privacy you can create a .getMethod for it.

public String getUsername(){
    return Username;
}

You can just create a model class with getters and setters:

class UserModel.java

public String Username;

public String getUserName()
{
    return Username;
}

public void setUserName(String USER_NAME)
{
   this.Username = USER_NAME;
}

In the main.java,

UserModel userObj = new UserModel();

txt_Username.addFocusListener(new FocusAdapter() {
    @Override
    public  void focusLost(FocusEvent arg0) {
 {
     userObj.setUserName(txt_Username.getText());
     //Username= txt_Username.getText();
 }
});

To retrieve it anywhere in main.java, use

  String userName = userObj.getUserName();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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