登录系统我不知道很热

时间:2015-12-15 21:37:12

标签: java database swing sqlite account

我正在使用swing进行java迷你游戏,因此它看起来像一个程序(因为我只是学习java +数据库)。现在我有登录系统,但我不知道该怎么做:

*当我登录时,我保持登录状态,直到o不关闭程序

*因为我想为我的帐户设置一个字符,并将字符统计信息保存到我的帐户ID

  ----> table account 
  ID: 2 
  Account:Yolo 
  Password:Swag
  -----------------> table Character 
  ID:"my id " 

Char姓名我想要的等等 所以我想问一下如何获得当前的accountid并将其插入到另一个包含char stats的表中?我学习所以不要怪我:)

`

static Connection connection = null;
Statement stmt = null;

    public JFrame LoginF;
    public JLabel UsernameL;
    public JLabel PasswordL;
    public JButton LoginB;
    public JTextField User;
    public JPasswordField Pass;


    public static void main(String args[]){

        Login log = new Login();
        log.Swing();
        connection=LoginIn.connector();
    }

    public void Swing(){
        LoginF = new JFrame("Game");
        LoginF.setSize(400,400);
        LoginF.getContentPane().setLayout(null);

        User = new JTextField();
        User.setBounds(219, 63, 86, 20);
        LoginF.getContentPane().add(User);
        User.setColumns(10);

        Pass = new JPasswordField();
        Pass.setBounds(219, 122, 86, 20);
        LoginF.getContentPane().add(Pass);

        JLabel UsernameL = new JLabel("Username");
        UsernameL.setBounds(65, 66, 69, 14);
        LoginF.getContentPane().add(UsernameL);

        JLabel PasswordL = new JLabel("Password");
        PasswordL.setBounds(65, 125, 69, 14);
        LoginF.getContentPane().add(PasswordL);

        JButton LoginB = new JButton("Login");
        LoginB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try{
                    String query="select * from AccountAdatok where Username=? and Password=?";
                    PreparedStatement pst=connection.prepareStatement(query);
                    pst.setString(1, User.getText());
                    pst.setString(2, Pass.getText());

                    ResultSet rs=pst.executeQuery();
                    int count=0;
                    while(rs.next()){
                        count=count+1;
                    }
                    if(count ==1)
                    {
                        JOptionPane.showMessageDialog(null, " Correct!");
                        LoginF.dispose();
                        MakeCharacter.main(arg0);
                    }
                    else if (count>1)
                    {
                        JOptionPane.showMessageDialog(null, " Cannot Duplicate!");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, " InCorret!");
                    }
                    rs.close();
                    pst.close();
                }catch(Exception e){
                    JOptionPane.showMessageDialog(null, e);
                }
                finally{
                    try{

                    }catch(Exception e){
                        JOptionPane.showMessageDialog(null, e);
                    }
                }
            }
        });
        LoginB.setBounds(145, 201, 89, 23);
        LoginF.getContentPane().add(LoginB);

        LoginF.setVisible(true);
    }

}`

2 个答案:

答案 0 :(得分:1)

首先分开责任的不同领域,你需要

  • 收集用户详细信息的一些方法
  • 验证用户详细信息的一些方法
  • 在用户登录后识别用户的某种方式

用户会话......

让我们从如何在用户登录后识别用户开始,例如,您可以执行类似的操作......

public interface User {
    public long getID();
    public String getName();
}

public class DefaultUser implements User {

    private final long id;
    private final String name;

    public DefaultUser(long id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public long getID() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

}

这是用户的一个非常基本的概念,它们具有名称和某种标识符,然后系统可以使用它来进一步生成与用户相关的数据。

验证...

好的,接下来,我们需要对用户进行身份验证。一般来说,UI(以及程序一般)不应该关心用户实际验证的机制,只需要关注它是以一种通用且众所周知的方式完成的,例如

public interface Authenticator {
    public User authenticate(String userName, char[] password) throws AuthenticationException;
}

public class AuthenticationException extends Exception {

    public AuthenticationException(String message) {
        super(message);
    }

    public AuthenticationException(String message, Throwable cause) {
        super(message, cause);
    }

}

所以这只是说明你可以将一些细节传递给某个实现,它会返回一个非空User或抛出一个AuthenticationException

数据库身份验证......

接下来,我们需要一些实际执行身份验证过程的Authenticator实现,如果有效,则生成User对象...

public class DatabaseAuthenticator implements Authenticator {

    private Connection connection;

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

    @Override
    public User authenticate(String userName, char[] password) throws AuthenticationException {
        User user = null;
        String query = "select * from AccountAdatok where Username=? and Password=?";
        try (PreparedStatement pst = connection.prepareStatement(query)) {
            pst.setString(1, userName);
            pst.setString(2, String.copyValueOf(password));

            try (ResultSet rs = pst.executeQuery()) {
                if (rs.next()) {
                    long id = rs.getLong("ID");
                    user = new DefaultUser(id, userName);
                } else {
                    throw new AuthenticationException("Authentication of " + userName + " failed");
                }
            }
        } catch (SQLException exp) {
            throw new AuthenticationException("Authentication of " + userName + " failed", exp);
        }
        return user;
    }

}

现在,你可能会问自己“为什么要全力以赴?”那么,除了为您提供一个可以轻松更改的系统(使用Web服务对用户进行身份验证的内容?简单,只需实现Authenticator的新实现)。

测试也更容易,因为您可以提供Authenticator的“模拟”实现,并可以非常轻松地测试系统的各种条件。

登录视图...

好吧,那么,这一切都很好,但是你怎么能真正使用它呢?

嗯,从字面上讲,您可以通过命令提示符提示用户输入凭据,或者从文件中读取它们,或者,如您所愿,使用某种基于Swing的表单

Login View

现在,你可以用一些额外的文字/说明,也许是徽标,但我会把它留给你。

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
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 javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class MyAwesomeProgram {

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

    public MyAwesomeProgram() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                Authenticator authenticator = new DatabaseAuthenticator(null);
                User user = LoginPane.showLoginDialog(null, authenticator);
                if (user != null) {
                    // Next stage of program
                } else {
                    // No valid user, do what you will
                }
            }
        });
    }

    public static class LoginPane extends JPanel {

        private JTextField userNameField;
        private JPasswordField passwordField;

        public LoginPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets = new Insets(2, 2, 2, 2);
            add(new JLabel("User name: "), gbc);
            gbc.gridy++;
            add(new JLabel("Password: "), gbc);

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

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

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

        public String getUserName() {
            return userNameField.getText();
        }

        public char[] getPassword() {
            return passwordField.getPassword();
        }

        public static User showLoginDialog(Component owner, Authenticator authenticator) {

            return new LoginDialogView(owner, authenticator).doLogin();

        }

        protected static class LoginDialogView {

            private User user;
            private JDialog dialog;

            public LoginDialogView(Component owner, Authenticator authenticator) {

                dialog = new JDialog(owner == null ? (Window) null : SwingUtilities.windowForComponent(owner));
                dialog.setModal(true);

                LoginPane loginPane = new LoginPane();
                loginPane.setBorder(new EmptyBorder(10, 10, 10, 10));
                dialog.add(loginPane);

                JPanel buttons = new JPanel();
                JButton ok = new JButton("Ok");
                JButton cancel = new JButton("Cancel");

                ok.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            user = authenticator.authenticate(loginPane.getUserName(), loginPane.getPassword());
                            dialog.dispose();
                        } catch (AuthenticationException ex) {
                            JOptionPane.showMessageDialog(dialog, ex.getMessage());
                        }
                    }
                });

                cancel.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        user = null;
                        dialog.dispose();
                    }
                });
                dialog.pack();
                dialog.setLocationRelativeTo(owner);
            }

            public User getUser() {
                return user;
            }

            public User doLogin() {
                dialog.setVisible(true);
                return getUser();
            }

        }

    }
}

在概念层面,这是Model-View-Controller范例的一部分,其中实际工作不是由视图完成的,而是由其他一些“控制器”执行

答案 1 :(得分:0)

制作登录屏幕非常简单,只需创建一个带有输入和验证的屏幕,另一个Java代码就在您的框架中。

按照这些简单的步骤操作,您应该可以登录。

  • 对于身份验证,我建议您创建一个对象来存储数据库中的数据,并将这些对象存储到arraylist中。

示例

private ArrayList<User> usrList;
private void downloadUsrData() {
    dbc = new DBConn(); //Ignore this, I am using a driver
    String query1 = "SELECT * FROM user_table";
    rs = dbc.getData(query1);
    try {
        while (rs.next()) {
            String username = rs.getString("username");
            String passwd = rs.getString("passwd");
            String fName = rs.getString("fName");
            String lName = rs.getString("lName");
            User usr = new User(username, passwd, fName, lName);
            usrList.add(usr);
        }
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        JOptionPane.showMessageDialog(null, "Request Failed"
                + "\nPossible Reasons are:"
                + "\n1- No connection to database"
                + "\n2- No data in database");
    }
  • 然后,当您输入数据时,然后通过与您的输入相匹配的arraylist与您的arraylist中的对象所持有的数据进行比较
  • 如果数据匹配正确,则将帧从一个java代码传递到另一个java代码 示例检查

     if (action.equals("Login")) {
        String usernameInput = usernameField.getText().toString();
        String passwdInput = passwdField.getText().toString();
    
        boolean isLoggedIn = false;
        passwdField.setText("");
    
        for (User usr : usrList) {
            if (usr.getUserName().equals(usernameInput)) {
                if (usr.getPassWd().equals(passwdInput)) {
                    isLoggedIn = true;
                    frame.getContentPane().removeAll();
                    GameScreen gmeScreen = new GameScreen(frame, usrList,
                            usr);
                }
            }
        }
        if (isLoggedIn == false) {
            JOptionPane.showMessageDialog(null,
                    "Username/Password may be In-correct");
        }
    }
    
  • 另外请确保您有另一个类构造函数,如果要注销,可以调用它,只需调用第二个修改构造函数

示例 构造函数1

 public LoginScreen() {
    usrList = new ArrayList<User>();
    initialize();
}

构建2

public LoginScreen(JFrame frame, ArrayList<User> usrList) {
    this.frame = frame;
    this.usrList= usrList;
}

简单(如果您需要,我会为您更新此内容)