java mysql swing 登录注册页面带有验证码 代码实现
时间: 2023-12-01 17:05:01 浏览: 112
Java+Swing 个人通讯录系统设计与实现
5星 · 资源好评率100%
好的,以下是一个简单的 Java Swing 登录页面,其中包含验证码的实现。假设您已经有了生成验证码图片的方法,我将在代码中使用一个名为 `generateCaptcha()` 的方法来代表该方法。此外,我们还将使用 MySQL 数据库来存储用户信息。
```java
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.sql.*;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel usernameLabel, passwordLabel, captchaLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton, registerButton, refreshButton;
private JPanel mainPanel, inputPanel, buttonPanel, captchaPanel;
private BufferedImage captchaImage;
private String captchaText;
private Connection conn;
public LoginFrame() {
initGUI();
initDB();
generateCaptcha();
}
private void initGUI() {
// 设置窗口标题和大小
setTitle("Login");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建输入框和标签
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
captchaLabel = new JLabel("Captcha:");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
// 创建验证码相关组件
captchaPanel = new JPanel();
refreshButton = new JButton("Refresh");
refreshButton.addActionListener(this);
captchaPanel.add(refreshButton);
// 创建登录和注册按钮
loginButton = new JButton("Login");
loginButton.addActionListener(this);
registerButton = new JButton("Register");
registerButton.addActionListener(this);
// 将组件添加到输入面板和按钮面板
inputPanel = new JPanel(new GridLayout(3, 2));
inputPanel.add(usernameLabel);
inputPanel.add(usernameField);
inputPanel.add(passwordLabel);
inputPanel.add(passwordField);
inputPanel.add(captchaLabel);
inputPanel.add(captchaPanel);
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(loginButton);
buttonPanel.add(registerButton);
// 将输入面板和按钮面板添加到主面板
mainPanel = new JPanel(new BorderLayout());
mainPanel.add(inputPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
// 将主面板添加到窗口
add(mainPanel);
}
private void initDB() {
try {
// 加载 MySQL 驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 连接到数据库
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private void generateCaptcha() {
// 生成验证码图片和文本
captchaText = generateRandomString(6);
captchaImage = new BufferedImage(120, 30, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = captchaImage.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 120, 30);
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial", Font.BOLD, 20));
g2d.drawString(captchaText, 10, 20);
g2d.dispose();
// 将验证码图片添加到面板
JLabel captchaImageLabel = new JLabel(new ImageIcon(captchaImage));
captchaPanel.removeAll();
captchaPanel.add(captchaImageLabel);
captchaPanel.add(refreshButton);
captchaPanel.revalidate();
}
private String generateRandomString(int length) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(chars.charAt((int) (Math.random() * chars.length())));
}
return sb.toString();
}
private boolean validateCaptcha(String input) {
return input.equalsIgnoreCase(captchaText);
}
private boolean validateLogin(String username, String password) {
try {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
return rs.next();
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
private boolean insertUser(String username, String password) {
try {
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
int result = stmt.executeUpdate();
return result > 0;
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
String captcha = JOptionPane.showInputDialog(this, "Please enter the captcha:");
if (validateCaptcha(captcha)) {
if (validateLogin(username, password)) {
JOptionPane.showMessageDialog(this, "Login successful!");
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password.");
}
} else {
JOptionPane.showMessageDialog(this, "Invalid captcha.");
generateCaptcha();
}
} else if (e.getSource() == registerButton) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (insertUser(username, password)) {
JOptionPane.showMessageDialog(this, "User registered successfully!");
} else {
JOptionPane.showMessageDialog(this, "Failed to register user.");
}
} else if (e.getSource() == refreshButton) {
generateCaptcha();
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setVisible(true);
}
}
```
这个示例代码中,我们使用了三个方法来验证用户输入的验证码、验证用户登录信息和向数据库中插入新用户。当用户点击登录按钮时,我们会弹出一个对话框来让用户输入验证码。如果验证码正确,我们将验证用户输入的用户名和密码是否正确,并给出相应的提示。当用户点击注册按钮时,我们将向数据库中插入新用户的信息。当用户点击刷新验证码按钮时,我们将生成新的验证码图片并更新面板。
上述代码仅供参考,您可以根据您的需求进行修改和扩展。
阅读全文