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

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

问题描述

我工作在java迷你游戏与摆动,所以它看起来像一个程序(因为我只是学习Java +数据库)。我有我的登录系统,但我不知道该如何做:



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



*因为我想为我的帐户创建一个字符字符统计到我的帐户ID所以

  ---->表帐户
ID:2
帐户:Yolo
密码:Swag
----------------->表格字符
ID:my id

Char name what my want etc
所以我想问如何获取当前accountid,并将其插入另一个表格与char stats?我学习,所以不要怪我:)






`

  static Connection connection = null; 
语句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 []){

登录日志= 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用户名L = 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,Can not 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);
}

}`

解决方案

从分开不同的责任区域开始,您需要





  • 验证用户详细信息的方式

  • 登录后识别用户的某种方式



    • 用户会话...



      让我们从您在登录后如何识别用户开始,例如,你可以做... ...

        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 其实际执行认证过程,并且如果有效,则生成用户对象...

        public class DatabaseAuthenticator implements Authenticator {

      private Connection connection;

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

      @Override
      public用户验证(String userName,char [] password)throws AuthenticationException {
      用户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的形式





      现在,你可以添加一些额外的文字/说明,也许是一个标志,但我会留给你。

        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 = LoginPane.showLoginDialog(null,authenticator);
      if(user!= null){
      / /程序的下一阶段
      } else {
      //没有有效的用户,做你想做的事
      }
      }
      });
      }

      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用户showLoginDialog(组件所有者,Authenticator验证器){

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

      }

      protected static class LoginDialogView {

      private用户;
      private JDialog对话框;

      public LoginDialogView(Component owner,Authenticator authenticator){

      dialog = new JDialog(owner == null?(Window)null:SwingUtilities.windowForComponent
      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用户getUser(){
      return user;
      }

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

      }

      }
      }

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


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

      }`

      解决方案

      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"

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

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