21xrx.com
2024-09-20 00:11:50 Friday
登录
文章检索 我的文章 写文章
Java实现登录界面的完整代码及详细步骤
2023-06-19 14:11:27 深夜i     --     --
Java Swing MySQL

在现代互联网应用程序中,用户认证是必不可少的一部分。在本教程中,我们将探讨如何使用Java编写一个简单的登录界面并实现用户认证。我们将使用Swing框架来实现GUI部分,并将用户信息存储在MySQL数据库中。

步骤1:设置MySQL数据库

在本教程中,我们将使用MySQL数据库来存储用户信息。因此,您需要安装MySQL,并创建一个名为“login_demo”的数据库。在该数据库中,我们将使用以下查询创建一个名为“users”的表:

CREATE TABLE `users` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `username` varchar(45) DEFAULT NULL,

 `password` varchar(45) DEFAULT NULL,

 PRIMARY KEY (`id`),

 UNIQUE KEY `username_UNIQUE` (`username`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

步骤2:创建Java项目

在Eclipse或IntelliJ IDEA中创建一个新Java项目。我们将把登录界面放在一个名为“LoginForm”的包中,并将其作为项目的主类。

步骤3:使用Swing创建登录界面

使用Swing框架创建一个简单的登录界面。我们将创建一个JFrame子类来实现该界面。以下是相关代码:

package LoginForm;

import javax.swing.*;

import java.awt.*;

public class Login extends JFrame{

  Container container=getContentPane();

  JLabel userLabel=new JLabel("USERNAME");

  JLabel passwordLabel=new JLabel("PASSWORD");

  JTextField userTextField=new JTextField();

  JPasswordField passwordField=new JPasswordField();

  JButton loginButton=new JButton("LOGIN");

  JButton resetButton=new JButton("RESET");

  JCheckBox showPassword=new JCheckBox("Show Password");

  Login()

  {

    setLayoutManager();

    setLocationAndSize();

    addComponentsToContainer();

    addActionEvent();

  }

  public void setLayoutManager()

  {

    container.setLayout(null);

  }

  public void setLocationAndSize()

  {

    userLabel.setBounds(50,150,100,30);

    passwordLabel.setBounds(50,220,100,30);

    userTextField.setBounds(150,150,150,30);

    passwordField.setBounds(150,220,150,30);

    showPassword.setBounds(150,250,150,30);

    loginButton.setBounds(50,300,100,30);

    resetButton.setBounds(200,300,100,30);

  }

  public void addComponentsToContainer()

  {

    container.add(userLabel);

    container.add(passwordLabel);

    container.add(userTextField);

    container.add(passwordField);

    container.add(showPassword);

    container.add(loginButton);

    container.add(resetButton);

  }

  public void addActionEvent()

  {

    //adding Action listener to components

    loginButton.addActionListener(this);

    resetButton.addActionListener(this);

    showPassword.addActionListener(this);

  }

  @Override

  public void actionPerformed(ActionEvent e) {

    //Coding Part of LOGIN button

    if (e.getSource() == loginButton) {

      String userText;

      String pwdText;

      userText = userTextField.getText();

      pwdText = passwordField.getText();

      if (userText.equalsIgnoreCase("admin") && pwdText.equalsIgnoreCase("admin")) {

        JOptionPane.showMessageDialog(this, "Login Successful");

      } else {

        JOptionPane.showMessageDialog(this, "Invalid Username or Password");

      }

    }

    //Coding Part of RESET button

    if (e.getSource() == resetButton) {

      userTextField.setText("");

      passwordField.setText("");

    }

    //Coding Part of showPassword JCheckBox

    if (e.getSource() == showPassword) {

      if (showPassword.isSelected()) {

        passwordField.setEchoChar((char) 0);

      } else {

        passwordField.setEchoChar('*');

      }

    }

  }

}

步骤4:添加数据库连接代码

我们将使用JDBC API连接到MySQL数据库。在您的Java项目中添加MySQL驱动程序JAR文件,并使用以下代码连接到数据库中的“users”表:

//declaring required objects and variables

Connection con;

ResultSet rs;

PreparedStatement pst;

String query;

//method to establish connection to the database

public Connection getConnection() {

  Connection con = null;

  try {

    con = DriverManager.getConnection("jdbc:mysql://hostname:port/login_demo?" + "user=root&password=");

  } catch (SQLException ex) {

    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);

  }

  return con;

}

//method to authenticate user credentials

public boolean authenticateUser(String username, String password) {

  boolean found = false;

  query = "SELECT * FROM users WHERE username=? AND password=?";

  try {

    con = getConnection();

    pst = con.prepareStatement(query);

    pst.setString(1, username);

    pst.setString(2, password);

    rs = pst.executeQuery();

    if (rs.next())

      found = true;

  } catch (SQLException e) {

    System.out.println(e.getMessage());

  }

  return found;

}

步骤5:完成登录功能

现在,我们可以将authenticateUser方法添加到登录按钮的动作侦听器中。如果该方法返回真,则用户将被重定向到新页面。否则,将提示用户输入正确的用户名和密码。以下是完整的Login类代码:

package LoginForm;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.*;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Login extends JFrame implements ActionListener {

  Container container = getContentPane();

  JLabel userLabel = new JLabel("USERNAME");

  JLabel passwordLabel = new JLabel("PASSWORD");

  JTextField userTextField = new JTextField();

  JPasswordField passwordField = new JPasswordField();

  JButton loginButton = new JButton("LOGIN");

  JButton resetButton = new JButton("RESET");

  JCheckBox showPassword = new JCheckBox("Show Password");

  Connection con;

  ResultSet rs;

  PreparedStatement pst;

  String query;

  Login() {

    setLayoutManager();

    setLocationAndSize();

    addComponentsToContainer();

    addActionEvent();

    con = getConnection();

  }

  public void setLayoutManager() {

    container.setLayout(null);

  }

  public void setLocationAndSize() {

    userLabel.setBounds(50, 150, 100, 30);

    passwordLabel.setBounds(50, 220, 100, 30);

    userTextField.setBounds(150, 150, 150, 30);

    passwordField.setBounds(150, 220, 150, 30);

    showPassword.setBounds(150, 250, 150, 30);

    loginButton.setBounds(50, 300, 100, 30);

    resetButton.setBounds(200, 300, 100, 30);

  }

  public void addComponentsToContainer() {

    container.add(userLabel);

    container.add(passwordLabel);

    container.add(userTextField);

    container.add(passwordField);

    container.add(showPassword);

    container.add(loginButton);

    container.add(resetButton);

  }

  public void addActionEvent() {

    loginButton.addActionListener(this);

    resetButton.addActionListener(this);

    showPassword.addActionListener(this);

  }

  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == loginButton) {

      String username;

      String password;

      username = userTextField.getText();

      password = passwordField.getText();

      if (authenticateUser(username, password)) {

        JOptionPane.showMessageDialog(this, "Login Successful");

        MainMenu mainMenu=new MainMenu();

        mainMenu.setVisible(true);

        dispose();

      } else {

        JOptionPane.showMessageDialog(this, "Invalid Username or Password");

      }

    }

    if (e.getSource() == resetButton) {

      userTextField.setText("");

      passwordField.setText("");

    }

    if (e.getSource() == showPassword) {

      if (showPassword.isSelected()) {

        passwordField.setEchoChar((char) 0);

      } else {

        passwordField.setEchoChar('*');

      }

    }

  }

  public Connection getConnection() {

    Connection con = null;

    try {

      con = DriverManager.getConnection("jdbc:mysql://localhost/login_demo?" + "user=root&password=");

    } catch (SQLException ex) {

      Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);

    }

    return con;

  }

  public boolean authenticateUser(String username, String password) {

    boolean found = false;

    query = "SELECT * FROM users WHERE username=? AND password=?";

    try {

      pst = con.prepareStatement(query);

      pst.setString(1, username);

      pst.setString(2, password);

      rs = pst.executeQuery();

      if (rs.next())

        found = true;

    } catch (SQLException e) {

      System.out.println(e.getMessage());

    }

    return found;

  }

  public static void main(String[] args) {

    Login login=new Login();

    login.setVisible(true);

    login.setTitle("Java Login Form");

    login.setBounds(10,10,370,600);

    login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    login.setResizable(false);

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复