登录模块在实际项目开发中很常见,请按照教材28页(PPT49页)利用单一职责原则重构后的类图实现这一模块。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
// MainClass is responsible for starting the system.public class MainClass {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Form");
LoginForm loginForm = new LoginForm(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
// LoginForm is responsible for displaying the login form and handling events.
public class LoginForm extends JFrame {
private UserDAO userDAO;
public LoginForm(JFrame frame) {
super("Login Form");
userDAO = new UserDAO();
// Add UI components and event handlers here
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setVisible(true);
}
// Event handler methods go here}
// UserDAO encapsulates all operations related to the users table.
public class UserDAO {
private DBUtil dbUtil;
public UserDAO() {
dbUtil = new DBUtil();
}
public boolean findUser(String userName, String userPassword) throws Exception { Connection connection = dbUtil.getConnection();
PreparedStatement statement = connection.prepareStatement( "SELECT * FROM Users WHERE username = ? AND password = ?");
statement.setString(1, userName);
statement.setString(2, userPassword);
ResultSet resultSet = statement.executeQuery();
return resultSet.next();
}
}
// DBUtil provides a connection to the database.
public class DBUtil {
private final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private final String USER = "root";
private final String PASSWORD = "20223959";
public Connection getConnection() throws Exception { Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
标签:JFrame,UserDAO,职责,原则,frame,单一,import,public,String From: https://www.cnblogs.com/pinganxile/p/18639497