Login System i dont know hot to do it [closed]

本秂侑毒 提交于 2019-12-19 12:52:13

问题


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:

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

*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 " 

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

}`


回答1:


Start by separating the different areas of responsibility, you need

  • Some way to gather user details
  • Some way to authenticate the user details
  • Some way to identify the user after they are logged in

User session...

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.

Authentication...

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

}

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

Database authentication...

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

}

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).

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.

Login View...

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

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

        }

    }
}

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"




回答2:


Making a login screen is really easy, just make a screen with input and validation and another Java code taking in your frame.

Follow these easy steps and you should be able to log In.

  • For authentication, I suggest you create an object to store data from your database and store those objects into an arraylist.

Example

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");
    }
  • Then when you've entered your data, you then go through your arraylist matching your input with data held by the objects in your arraylist
  • If data is matched correctly, pass frame from one java code to another Example Checker

     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");
        }
    }
    
  • Also make sure you have another class constructor that you can call if you want to logout, you just recall the second modded constructor

Example constructor 1

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

construct 2

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

Simple (I will update this more for you if you need it)



来源:https://stackoverflow.com/questions/34299864/login-system-i-dont-know-hot-to-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!