登录系统我不知道很热

我正在研究带有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); } 

}`

首先要分离责任的不同领域

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

用户会话……

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

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

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

validation…

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

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

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

数据库认证……

接下来,我们需要一些Authenticator实现执行身份validation过程,如果有效,则生成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服务对用户进行身份validation的内容?简单,只需实现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 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(); } } } } 

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

创建一个登录屏幕非常简单,只需创建一个带有输入和validation的屏幕,并在框架中使用另一个Java代码。

按照这些简单的步骤,您应该能够登录。

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

 private ArrayList 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代码传递到另一个示例 检查器

      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"); } } 
  • 还要确保你有另一个类构造函数,如果你想注销你可以调用,你只需要调用第二个modded构造函数

示例 构造函数1

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

构造2

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

简单(如果您需要,我会更新更新)