2024/10/6
软件设计实验一:
[实验任务二]:单一职责原则 登录模块在实际项目开发中很常见,请按照教材28页(PPT49页)利用单一职责原则重构后的类图实现这一模块。 实验要求: 1. 提交源代码和对应的数据库文件(注意将此模块保存,以备以后使用); MainClass: public class MainClass { public static void main(String[] args) { new LoginForm(); } } LoginForm: public class LoginForm { private JTextField usernameField; private JPasswordField passwordField; private JButton loginButton; public LoginForm() { JFrame frame = new JFrame("登录"); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); JLabel usernameLabel = new JLabel("用户名:"); usernameLabel.setBounds(10, 20, 80, 25); frame.add(usernameLabel); usernameField = new JTextField(20); usernameField.setBounds(100, 20, 165, 25); frame.add(usernameField); JLabel passwordLabel = new JLabel("密码:"); passwordLabel.setBounds(10, 50, 80, 25); frame.add(passwordLabel); passwordField = new JPasswordField(20); passwordField.setBounds(100, 50, 165, 25); frame.add(passwordField); loginButton = new JButton("登录"); loginButton.setBounds(10, 80, 255, 25); frame.add(loginButton); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleLogin(); } }); frame.setVisible(true); } private void handleLogin() { String username = usernameField.getText(); String password = new String(passwordField.getPassword()); if (UserDAO.login(username, password)) { JOptionPane.showMessageDialog(null, "登录成功"); } else { JOptionPane.showMessageDialog(null, "用户名或密码错误"); } } public static void main(String[] args) { new LoginForm(); } } UserDAO: public class UserDAO { public static boolean login(String username, String password) { Connection conn = DBUtil.getConnection(); try { String sql = "SELECT * FROM users WHERE username = ? AND password = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, username); pstmt.setString(2, password); ResultSet rs = pstmt.executeQuery(); return rs.next(); // 如果能找到用户则登陆成功 } catch (SQLException e) { e.printStackTrace(); return false; } finally { DBUtil.closeConnection(conn); } } } DBUtil: public class DBUtil { private static final String URL = "jdbc:mysql://localhost:3306/design"; private static final String USER = "root"; private static final String PASSWORD = "1234"; public static Connection getConnection() { try { return DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { e.printStackTrace(); return null; } } public static void closeConnection(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } 数据库设计部分: create database design; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, -- 用户唯一标识 username VARCHAR(50) NOT NULL UNIQUE, -- 用户名,唯一 password VARCHAR(255) NOT NULL -- 密码 ); insert into users(username,password) values('20223717','20223717');