登录系统我不知道热做 [英] Login System i dont know hot to do it

查看:27
本文介绍了登录系统我不知道热做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发带有 Swing 的 java 迷你游戏,所以它看起来像一个程序(因为我只是学习 java + 数据库).现在我有登录系统,但我不知道该怎么做:

I working on java mini game with swing so its look like a program(Cause i just learn java + database).Now i have login system but i don't know how to do it:

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

*when i login i stay logged in until o do not close program

*因为我想为我的帐户创建一个字符并将字符统计信息保存到我的帐户 ID 中,所以

*because i want to make a char for my account and save character stats to my account id so

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

字符名称我想要什么等所以我想问一下如何获取当前的 accountid 并将其插入到另一个带有 char stats 的表中?我正在学习,所以不要怪我:)

Char name what i want etc so i want to ask how to get current accountid and insert it to another table with char stats?i learning so don't blame me:)

`

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);
    }

}`

推荐答案

从分离不同的责任领域开始,你需要

Start by separating the different areas of responsibility, you need

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

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

Let's start with how you might identify the user after they are logged in, for example, you could do something like...

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;
    }

}

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

This is a very basic concept of a user, they have name and some kind of identifier, which the system can then use to further generate data associated with the user.

好的,接下来,我们需要某种方式来验证用户.一般来说,用户界面(以及一般的程序)不应该关心用户实际通过何种机制进行身份验证,只需要以一种常见且众所周知的方式进行,例如

Okay, next, we need someway to authenticate the user. Generally speaking, the UI (and the program generally) shouldn't care about the mechanisms by which a user is actually authenticated, only that it is done in a common and well known manner, for example

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

So this simply states that you can pass some details to some implementation and it will either return a non-null User or throw an AuthenticationException

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

Next we need some implementation of the Authenticator which actually performs the authentication process and, if valid, generates a User object...

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 的新实现即可).

Now, you might be asking yourself "why go to all the trouble?" Well, apart from providing you with a system which can be easily changed (what to use a web service to authenticate the user? Simple, just implement a new implementation of Authenticator).

它也更容易测试,因为您可以提供一个模拟"的Authenticator 的实现,并非常容易地测试系统的各种条件.

It's also much easier to test, as you can provide a "mocked" implementation of the Authenticator and test various conditions of your system very easily.

好的,所以,这一切都很好,但您实际上如何使用所有这些?

Okay, so, that's all fine and good, but how might you actually use all that?

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

Well, you could, literally, prompt the user for their credentials via the command prompt or read them from a file or, as you seem to want to do, use some kind of Swing based form

现在,你可以用一些额外的文字/说明来美化它,也许是一个标志,但我会把它留给你.

Now, you could pretty it up with some additional text/instructions, maybe a logo, but I'll leave that up to you.

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 范式,其中实际工作不是由视图完成,而是由其他控制器"执行

At a conceptual level, this is part of a Model-View-Controller paradigm, where the actual work is not done by the view, but is performed by some other "controller"

这篇关于登录系统我不知道热做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆