簡體   English   中英

登錄系統Java和postgresql

[英]Login system Java and postgresql

我已經嘗試了一個星期來讓它工作,但我找不到任何好的東西來幫助我解決問題。

我嘗試制作一個ATM程序,與數據庫的連接正常,但我不知道如何檢查我在程序中引入的用戶名和密碼是否與我在數據庫中的相同,檢查后我希望它向我發送消息“成功”並彈出一個新的 window。

現在只是顯示我在數據庫中的內容。

對不起,如果我要求太多,但我是初學者。

這是主要代碼:

import java.beans.Statement;
    import java.sql.Connection;
    import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;


    import javax.swing.JFrame;
    import javax.swing.JTextField;


import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JSeparator;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

    public class ProgramBanca2 extends JFrame {
        /**
         * 
         */
        private static final long serialVersionUID = -7748785395531780446L;
        public static void main(String[] args) {
            String jdbcURL = "jdbc:postgresql://localhost:5432/Banca2";
            String username = "postgres";
            String password = "postgres";
            try {
                Connection connection = DriverManager.getConnection(jdbcURL, username, password);
                System.out.print("Connected to postgres");
                ProgramBanca2 window = new ProgramBanca2();
                window.setVisible(true);
                window.setBounds(200, 200, 450, 400);
                String sql = "Select * from login";
                
                java.sql.Statement statement =  connection.createStatement();

                ResultSet result = statement.executeQuery(sql);
                
                
                while (result.next()) {
                    int id = result.getInt("id");
                    String nume = result.getString("name");
                    int parola = result.getInt("password");
                    
                    System.out.printf(" %s - %d\n ", nume, parola);

                    
                }
                }
                
                connection.close();
                
            }catch (SQLException e){
                System.out.print("Cannot connect to postgres");
                e.printStackTrace();
            }
        }

這是設計:

private JTextField parola;
        private JTextField nume;
        public ProgramBanca2() {
            getContentPane().setBackground(new Color(0, 206, 209));
            setBackground(new Color(0, 206, 209));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().setLayout(null);
            setResizable(false);

            
            parola = new JTextField();
            parola.setFont(new Font("Sitka Subheading", Font.PLAIN, 18));
            parola.setBounds(141, 159, 211, 46);
            getContentPane().add(parola);
            parola.setColumns(10);
            
            JLabel lblNewLabel = new JLabel("Parola");
            lblNewLabel.setFont(new Font("Sitka Small", Font.BOLD, 17));
            lblNewLabel.setBounds(15, 156, 130, 50);
            getContentPane().add(lblNewLabel);
            
            JLabel lblNewLabel_1 = new JLabel("Nume");
            lblNewLabel_1.setFont(new Font("Sitka Small", Font.BOLD, 17));
            lblNewLabel_1.setBounds(15, 79, 130, 50);
            getContentPane().add(lblNewLabel_1);
            
            nume = new JTextField();
            nume.setFont(new Font("Sitka Subheading", Font.PLAIN, 18));
            nume.setBounds(141, 82, 211, 46);
            getContentPane().add(nume);
            nume.setColumns(10);
            
            
            JButton btnNewButton = new JButton("Login");
            btnNewButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
    
            
                }
            });
            btnNewButton.setFont(new Font("Sitka Small", Font.PLAIN, 15));
            btnNewButton.setBounds(10, 238, 155, 100);
            getContentPane().add(btnNewButton);
            
            JButton btnNewButton_1 = new JButton("Reset");
            btnNewButton_1.setFont(new Font("Sitka Small", Font.PLAIN, 15));
            btnNewButton_1.setBounds(245, 238, 141, 100);
            getContentPane().add(btnNewButton_1);
            
            JSeparator separator = new JSeparator();
            separator.setBounds(10, 215, 376, 2);
            getContentPane().add(separator);
            
            JSeparator separator_1 = new JSeparator();
            separator_1.setBounds(15, 65, 376, 2);
            getContentPane().add(separator_1);


        }
    }

因此,核心問題是,您仍然以程序方式思考, CB之后,在A之后,因為大多數 GUI 以“事件驅動”的方式工作,所以會發生一些事情,然后您對其做出響應。

我的意思是,目前你正在做:

  • 顯示 window
  • 驗證用戶

在您嘗試驗證憑據之前,用戶沒有機會輸入詳細信息。

相反,您需要退后一步,了解 Swing/GUI 的工作原理:

擁有並理解以下內容也無妨:

讓我們從一些授權開始。 登錄視圖不關心用戶“如何”被認證,它應該關心的是,當它需要時,它可以請求對用戶憑證進行認證,如果它們是正確的,它會得到某種“用戶”表示返回,或者如果出現問題則出錯,例如......

public interface User {
    public String getUserName();
}

public interface AuthentationDelegate {
    public User authenticateUser(String userName, char[] password) throws Exception;
}

漂亮而簡單。

現在我們有了,我們可以看看登錄視圖......

public class LoginPane extends JPanel {
    
    public interface Observer {
        public void didLoginUser(LoginPane source, User user);
        public void didCancelLogin(LoginPane source);
    }

    private JTextField userNameField;
    private JPasswordField passwordField;
    
    public LoginPane(Observer observer, AuthentationDelegate authentationDelegate) {
        setLayout(new GridBagLayout());
        
        userNameField = new JTextField(10);
        passwordField = new JPasswordField(10);
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(4, 4, 4, 4);
        gbc.anchor = gbc.LINE_END;
        
        add(new JLabel("User name:"), gbc);
        gbc.gridy++;
        add(new JLabel("Password:"), gbc);

        gbc.gridx++;
        gbc.gridy = 0;
        gbc.anchor = gbc.LINE_START;
        
        add(userNameField, gbc);
        gbc.gridy++;
        add(passwordField, gbc);
        
        JPanel actionPanel = new JPanel(new GridLayout(1, 2));
        JButton loginButton = new JButton("Login");
        JButton cancelButton = new JButton("Cancel");
        
        actionPanel.add(loginButton);
        actionPanel.add(cancelButton);
        
        gbc.gridy++;
        gbc.gridx = 0;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.anchor = gbc.CENTER;
        add(actionPanel, gbc);
        
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try { 
                    User user = authentationDelegate.authenticateUser(userNameField.getText(), passwordField.getPassword());
                    if (user != null) {
                        observer.didLoginUser(LoginPane.this, user);
                    } else {
                        JOptionPane.showMessageDialog(LoginPane.this, "Failed to authenticate user", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception exp) {
                    JOptionPane.showMessageDialog(LoginPane.this, "Failed to authenticate user", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                observer.didCancelLogin(LoginPane.this);
            }
        });
    }

}

這是非常基本的,它顯示用戶名和密碼的字段,當單擊登錄按鈕時,它將嘗試通過代理驗證用戶詳細信息。

它還提供了一個觀察者回調來通知演示者一些 state 已經改變並且他們可能想要采取某種行動。

好的,現在讓我們開始實際實施身份驗證工作流程......

// You probably want to fill this out with some details
// from the database properties
public class DefaultUser implements User {
    private String username;

    public DefaultUser(String username) {
        this.username = username;
    }

    @Override
    public String getUserName() {
        return username;
    }

}

public class SQLAuthentationDelegate implements AuthentationDelegate {
    
    private Connection connection;

    public SQLAuthentationDelegate(Connection connection) {
        this.connection = connection;
    }

    @Override
    public User authenticateUser(String userName, char[] password) throws Exception {
        try (PreparedStatement stmt = connection.prepareStatement("select * from login where username = ? and password = ?")) {
            stmt.setString(1, userName);
            stmt.setString(2, new String(password));
            
            try (ResultSet rs = stmt.executeQuery()) {
                // It should only have one result
                if (rs.next()) {
                    // I don't know, load some properties which
                    // are important, like the record key or something
                    // maybe the display name or other important information
                    return new DefaultUser(userName);
                }
            }
        }
        return null;
    }
    
}

所以,整個類的職責是只做一件事,驗證用戶憑據,這是非常基本的,你需要填寫它,但它讓你了解它是如何工作的,哦,你應該看看Using Prepared Statements ,哦,你可能還想看看像Introduction to SQL這樣的東西。

現在,讓我們把它放在一起......

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                // Make you connection here...
                Connection connection = null;
                JFrame frame = new JFrame();
                frame.add(new LoginPane(new LoginPane.Observer() {
                    @Override
                    public void didLoginUser(LoginPane source, User user) {
                        // User was authenticated, do something
                    }

                    @Override
                    public void didCancelLogin(LoginPane source) {
                        SwingUtilities.windowForComponent(source).dispose();
                    }
                }, new SQLAuthentationDelegate(connection)));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

但是為什么(付出所有這些努力)?

因為,從長遠來看,它會讓你的生活更輕松,例如,當我測試 UI 的交互時,我創建了一個簡單的AuthentationDelegate並且只需更改一行,我就可以切換工作流。 ..

public class DefaultAuthentationDelegate implements AuthentationDelegate {
    @Override
    public User authenticateUser(String userName, char[] password) throws Exception {
        return new DefaultUser(userName);
    }
}

JFrame frame = new JFrame();
frame.add(new LoginPane(new LoginPane.Observer() {
    @Override
    public void didLoginUser(LoginPane source, User user) {
        // User was authenticated, do something
        JOptionPane.showMessageDialog(null, "All your money is belong to us", "Welcome", JOptionPane.PLAIN_MESSAGE);
        SwingUtilities.windowForComponent(source).dispose();
    }

    @Override
    public void didCancelLogin(LoginPane source) {
        SwingUtilities.windowForComponent(source).dispose();
    }
}, new DefaultAuthentationDelegate()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

而代碼的 rest 將繼續工作

可運行的例子...

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.sql.*;
import javax.swing.SwingUtilities;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                // Make you connection here...
                Connection connection = null;
                JFrame frame = new JFrame();
                frame.add(new LoginPane(new LoginPane.Observer() {
                    @Override
                    public void didLoginUser(LoginPane source, User user) {
                        // User was authenticated, do something
                        JOptionPane.showMessageDialog(null, "All your money is belong to us", "Welcome", JOptionPane.PLAIN_MESSAGE);
                        SwingUtilities.windowForComponent(source).dispose();
                    }

                    @Override
                    public void didCancelLogin(LoginPane source) {
                        SwingUtilities.windowForComponent(source).dispose();
                    }
                }, new SQLAuthentationDelegate(connection)));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface User {
        public String getUserName();
    }

    public interface AuthentationDelegate {
        public User authenticateUser(String userName, char[] password) throws Exception;
    }

    // You probably want to fill this out with some details
    // from the database properties
    public class DefaultUser implements User {
        private String username;

        public DefaultUser(String username) {
            this.username = username;
        }

        @Override
        public String getUserName() {
            return username;
        }

    }

    public class DefaultAuthentationDelegate implements AuthentationDelegate {
        @Override
        public User authenticateUser(String userName, char[] password) throws Exception {
            return new DefaultUser(userName);
        }
    }

    public class SQLAuthentationDelegate implements AuthentationDelegate {

        private Connection connection;

        public SQLAuthentationDelegate(Connection connection) {
            this.connection = connection;
        }

        @Override
        public User authenticateUser(String userName, char[] password) throws Exception {
            try (PreparedStatement stmt = connection.prepareStatement("select * from login where username = ? and password = ?")) {
                stmt.setString(1, userName);
                stmt.setString(2, new String(password));

                try (ResultSet rs = stmt.executeQuery()) {
                    // It should only have one result
                    if (rs.next()) {
                        // I don't know, load some properties which
                        // are important, like the record key or something
                        // maybe the display name or other important information
                        return new DefaultUser(userName);
                    }
                }
            }
            return null;
        }

    }

    public class LoginPane extends JPanel {

        public interface Observer {
            public void didLoginUser(LoginPane source, User user);

            public void didCancelLogin(LoginPane source);
        }

        private JTextField userNameField;
        private JPasswordField passwordField;

        public LoginPane(Observer observer, AuthentationDelegate authentationDelegate) {
            setLayout(new GridBagLayout());

            userNameField = new JTextField(10);
            passwordField = new JPasswordField(10);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.anchor = gbc.LINE_END;

            add(new JLabel("User name:"), gbc);
            gbc.gridy++;
            add(new JLabel("Password:"), gbc);

            gbc.gridx++;
            gbc.gridy = 0;
            gbc.anchor = gbc.LINE_START;

            add(userNameField, gbc);
            gbc.gridy++;
            add(passwordField, gbc);

            JPanel actionPanel = new JPanel(new GridLayout(1, 2));
            JButton loginButton = new JButton("Login");
            JButton cancelButton = new JButton("Cancel");

            actionPanel.add(loginButton);
            actionPanel.add(cancelButton);

            gbc.gridy++;
            gbc.gridx = 0;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = gbc.CENTER;
            add(actionPanel, gbc);

            loginButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        User user = authentationDelegate.authenticateUser(userNameField.getText(), passwordField.getPassword());
                        if (user != null) {
                            observer.didLoginUser(LoginPane.this, user);
                        } else {
                            JOptionPane.showMessageDialog(LoginPane.this, "Failed to authenticate user", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (Exception exp) {
                        JOptionPane.showMessageDialog(LoginPane.this, "Failed to authenticate user", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
            cancelButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    observer.didCancelLogin(LoginPane.this);
                }
            });
        }

    }
}

暫無
暫無

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

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