簡體   English   中英

如何從其他類或方法中“提取”變量?

[英]How do I “extract” a variable from other classes or methods?

在花了很多時間使用Python之后,我最近又回到了Java,並且我試圖再次使它適應。 我的第一個期望項目是制作一個小型應用程序,您可以在該應用程序中(首先)登錄。我正在使用mySQL來保存用戶名和密碼的數據庫。

到目前為止,我已經使用Java的swing GUI制作了一個彈出框,要求輸入登錄信息。 輸入的用戶名和密碼將對照SQL表中的用戶名和密碼進行測試。

問題是我正在使用while循環來對照SQL表測試輸入。 因此,將對照從SQL表創建的Hashmap中的每個鍵和值檢查輸入的信息。

我不確定如何從while循環和SQL的try語句中“提取”變量g(Hashmap),以便在將mySQL的數據填充到變量g之后,可以使用它。

我正在使用Eclipse(Java Neon)。

我不知道如何“提取”哈希表,當我嘗試使用while循環或try語句返回哈希表時,Eclipse會通知我void方法無法返回值(顯然)。 但是,我無法將返回類型從void更改為HashMap)String,String>,因為“返回類型與ActionListener.actionPerformed(ActionEvent e)不兼容”和“實現java.awt.event.ActionListener.actionPerformed”。

這是我的代碼:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

public class Hello0 extends JFrame {
    private static final long serialVersionUID = 1487932324102279819L;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Frame Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 200);

        JPanel panel = new JPanel();
        frame.add(panel);
        placeComponents(panel);

        frame.setVisible(true);
    }


    private static void placeComponents(JPanel panel) {

        panel.setLayout(null);
        JLabel userLabel = new JLabel("Username");
        userLabel.setBounds(10, 20, 80, 25);
        panel.add(userLabel);

        JTextField userText = new JTextField(20);
        userText.setBounds(100, 20, 165, 25);
        panel.add(userText);

        JLabel passwordLabel = new JLabel("Password");
        passwordLabel.setBounds(10, 50, 80, 25);
        panel.add(passwordLabel);

        JPasswordField passwordText = new JPasswordField(20);
        passwordText.setBounds(100, 50, 165, 25);
        panel.add(passwordText);

        JButton loginB = new JButton("Login");
        loginB.setBounds(10, 80, 80, 25);
        panel.add(loginB);

        loginB.addActionListener(new ActionListener() {

            public HashMap<String, String> actionPerformed(ActionEvent e) {
                String username0 = "root";
                String password = "javaSQLmy98";
                try {

                    String url = "jdbc:mysql://localhost:3306/javabase?useSSL=false";
                    Connection connection = DriverManager.getConnection(url, username0, password);
                    PreparedStatement stmt0 = connection.prepareStatement("SELECT * from userids");

                    String pass0 = null;
                    String user1 = userText.getText().toString();
                    char[] pass1 = passwordText.getPassword();
                    pass0 = String.valueOf(pass1);
                    System.out.println(user1);
                    System.out.println(pass1);

                    ResultSet rs = stmt0.executeQuery();
                    rs = stmt0.executeQuery("SELECT * from userids ");
                    while (rs.next()) {

                        String user = rs.getString("username");
                        String pass = rs.getString("paswrd");

                        Map<String, String> g = new HashMap<>();
                        g.put(user, pass);
                        return g;
                        // This was the alternative: if(g.keySet().contains("Jacob") && g.values().contains("root")) {


                        /*This code below was originally outside the while loop but I could not
                        figure out how to make it work without it being inside, and accessible 
                        to the hashmap g. Now it is being checked each time the while loop 
                        is ran, with a new pair of usernames and passwords on each loop. */

                        if (user1.equals(user) && pass0.equals(pass)) {
                            System.out.println("Good!");
                        }

                        /*The problem here is that the checker IS inside the loop, so it 
                         tests the input against each of the entries in the SQL table. */
                        else {
                            System.err.println("The username or password is incorrect.");
                        }
                    }

                    connection.close();
                } catch (Exception e1) {
                    System.err.println(e1.getMessage());
                }

            }
        });

    }

}

干杯!

要在while之外訪問g ,您需要在while外部聲明它,因為Java中的每個{}都將其內部的變量作為作用域。 從而,

Map<String, String> g = new HashMap<>();
while (condition) {
    // do something
    g.put(key, value);
}
// do something with g

但是在這種情況下,您可以直接在SQL中進行檢查,這樣會更加有效。


邊注:

不要存儲密碼。 不要存儲密碼。 哈希+鹽密碼(或更好的是,使用庫)。

嘗試這個:

Map<String, String> g = new HashMap<String, String>();
while(rs.next()) {
    String user = rs.getString("username");
    String pass = rs.getString("paswrd");
    g.put(user, pass);

    .....
}

注意:在HasmMap中將用戶名作為鍵不是一個好的編程,因為可以有多個具有相同名稱的用戶。

如果在查詢中添加WHERE子句,它將僅返回與條件匹配的數據。 換句話說,下面的查詢(顯然具有正確的值)將返回指定的userid條目(如果存在),否則將返回空結果集。

SELECT * from userids
WHERE userName = 'user1'
AND passwrd = 'pass1'

然后,您可以取消整個while循環和HashMap,並可以將代碼簡化如下:

if (rs.next()) {
    System.out.println("Good!");
} else {
    System.err.println("The username or password is incorrect.");
}

另外,如前所述,如果這不僅僅是編程練習,則應將密碼散列而不是存儲在純文本中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM