C.2 2022-11-29 19:30 采纳率: 41.2%
浏览 60
已结题

数据库插入数据,登录界面跳转失败

导入数据库查询的时候,连接不上去
public class AdminDO {
    private Integer id;
    private String userName;
    private String pwd;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}


public class LoginHandler extends KeyAdapter implements ActionListener {

    private LoginView loginView;

    public LoginHandler(LoginView loginView) {
        this.loginView = loginView;
    }

    public void actionPerformed(ActionEvent e) {
        JButton Jbutton = (JButton) e.getSource();
        String text = Jbutton.getText();
        if ("登录".equals(text)) {
            login();
        }
    }

    private void login() {
        String username = loginView.getUsernametext().getText();
        char[] chars = loginView.getPasswordtext().getPassword();
        if (username == null || "".equals(username.trim()) || chars == null) {
            JOptionPane.showMessageDialog(loginView, "用户名密码必填");
            return;
        }
        String password = new String(chars);
        System.out.println(username + ":" + password);

        if (username == null || "".equals(username.trim()) ||
                password == null || "".equals(password.trim())) {

        }
        //查询DB

        AdminService adminService = new AdminServiceImpl();
        AdminDO adminDO = new AdminDO();
        adminDO.setUserName(username);
        adminDO.setPwd(password);
        boolean flag = adminService.validateAdmin(adminDO);

        if (flag) {
            //跳转主界面销毁登录界面
            new MainView();
            loginView.dispose();
        } else {
            JOptionPane.showMessageDialog(loginView, "用户名密码错误");
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            login();
        }
    }

public class StudentRequest {
    private int pageNow;
    private int pageSize;
    private int start;
    private String searchKey;


    public int getStart() {
        return (pageNow -1) * pageSize;
    }


    public int getPageNow() {
        return pageNow;
    }

    public void setPageNow(int pageNow) {
        this.pageNow = pageNow;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public String getSearchKey() {
        return searchKey;
    }

    public void setSearchKey(String searchKey) {
        this.searchKey = searchKey;
    }
}

public class TableDTO {
    private  Vector<Vector<Object>> data;
    private int totalCount;

    public Vector<Vector<Object>> getData() {
        return data;
    }

    public void setData(Vector<Vector<Object>> data) {
        this.data = data;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
}


public class AdminServiceImpl implements AdminService {
    public boolean validateAdmin(AdminDO adminDO) {
        String userName = adminDO.getUserName();
        String pwdParam = adminDO.getPwd();
        String sql = "select pwd from user where user_name = ?";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            conn = DBUtil.getConn();
            if (conn == null) {
                return false;
            }
            ps = conn.prepareStatement(sql);
            ps.setString(1, userName);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                String pwd = resultSet.getString(1);
                if (adminDO.getPwd().equals(pwd)) {
                    return true;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            DBUtil.closeRs(resultSet);
            DBUtil.closeConn(conn);
            DBUtil.closePs(ps);

        }

        return false;
    }
}

    public TableDTO retrieveStudents(StudentRequest request) {
        StringBuilder sql = new StringBuilder();
        sql.append("select * from student ");
        if (request.getSearchKey() != null && !"".equals(request.getSearchKey().trim())) {
            sql.append(" where name like '%" + request.getSearchKey().trim() + "%' ");
        }
        sql.append("order by id desc limit ").append(request.getStart()).append(",").append(request.getPageSize());
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        TableDTO returnDTO = new TableDTO();

        try {
            conn = DBUtil.getConn();
            ps = conn.prepareStatement(sql.toString());
            rs = ps.executeQuery();
            //查询记录

            returnDTO.setData(fillData(rs));
            sql.setLength(0);
            sql.append("select count (*) from student ");
            if (request.getSearchKey() != null && !"".equals(request.getSearchKey().trim())) {
                sql.append(" where name like '%" + request.getSearchKey().trim() + "%' ");
            }

            ps = conn.prepareStatement(sql.toString());
            rs = ps.executeQuery();
            while (rs.next()) {
                int count = rs.getInt(1);
                returnDTO.setTotalCount(count);

            }
            return returnDTO;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeRs(rs);
            DBUtil.closePs(ps);
            DBUtil.closeConn(conn);
        }

        return null;
    }

    private Vector<Vector<Object>> fillData(ResultSet rs) throws SQLException {
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            //处理查出的每一条记录
            Vector<Object> oneRecord = new Vector<Object>();
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String no = rs.getString("no");
            int chinese = rs.getInt("chinese");
            int english = rs.getInt("english");
            int math = rs.getInt("math");
            int totalScore = chinese + english + math;
            oneRecord.addElement(id);
            oneRecord.addElement(name);
            oneRecord.addElement(no);
            oneRecord.addElement(chinese);
            oneRecord.addElement(english);
            oneRecord.addElement(math);
            oneRecord.addElement(totalScore);
            data.addElement(oneRecord);

        }
        return data;
    }
}


public interface AdminService {
     boolean validateAdmin(AdminDO adminDO);


}

public interface StudentService {

    TableDTO retrieveStudents(StudentRequest request);


}


public class MainViewCellRender extends DefaultTableCellRenderer {
    //在每一行的每一列显示之前都会调用
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (row % 2 == 0) {
            setBackground(Color.GRAY);
        } else {

            setBackground(Color.white);
        }
        setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }
}


public class MainViewTable extends JTable {

    public MainViewTable() {


        JTableHeader tableHeader = getTableHeader();
        tableHeader.setFont(new Font(null, Font.BOLD, 16));
        tableHeader.setForeground(Color.red);
        setFont(new Font(null, Font.PLAIN, 14));
        setForeground(Color.BLACK);
        setGridColor(Color.BLACK);
        setRowHeight(30);
        //设置多行选择
        getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    }


    public void setDataModel(MainViewTableModel mainViewTableModel) {
        this.setModel(mainViewTableModel);
    }


    public void renderRule() {
        Vector<String> columns1 = MainViewTableModel.getColumns();

        MainViewCellRender render = new MainViewCellRender();
        for (int i = 0; i < columns1.size(); i++) {
            TableColumn column = getColumn(columns1.get(i));
            column.setCellRenderer(render);
            if (i == 0) {
                column.setPreferredWidth(50);
                column.setMaxWidth(50);
                column.setResizable(false);
            }
        }


    }
}


public class MainViewTableModel extends DefaultTableModel {

    static Vector<String> columns1 = new Vector<String>();

    static {
        columns1.addElement("编号");
        columns1.addElement("姓名");
        columns1.addElement("学号");
        columns1.addElement("家乡");
        columns1.addElement("语文");
        columns1.addElement("数学");
        columns1.addElement("英语");
        columns1.addElement("总分");


    }

    private MainViewTableModel() {
        super(null, columns1);
    }

    private static MainViewTableModel mainViewTableModel = new MainViewTableModel();

    public static MainViewTableModel assembleModel(Vector<Vector<Object>> data) {
        mainViewTableModel.setDataVector(data, columns1);
        return mainViewTableModel;
    }

    public static Vector<String> getColumns() {
        return columns1;
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
}



public class LoginView extends JFrame {

    JLabel namelabel = new JLabel("学生成绩管理系统");
    JLabel username = new JLabel("用户名:");
    JLabel password = new JLabel("密码:");
    JTextField usernametext = new JTextField();
    JPasswordField passwordtext = new JPasswordField();
    JButton login = new JButton("登录");


    LoginHandler loginHandler;


    public LoginView() {


        loginHandler = new LoginHandler(this);


        setLayout(null);


        namelabel.setFont(new Font("华文行楷", Font.PLAIN, 40));
        username.setFont(new Font("华文行楷", Font.PLAIN, 15));
        password.setFont(new Font("华文行楷", Font.PLAIN, 15));


        Container c1 = getContentPane();

        c1.add(namelabel);
        c1.add(username);
        c1.add(password);
        c1.add(usernametext);
        c1.add(passwordtext);
        c1.add(login);

        //事件
        login.addActionListener(loginHandler);
        login.addKeyListener(loginHandler);


        namelabel.setBounds(130, 0, 400, 200);
        username.setBounds(190, 70, 200, 200);
        password.setBounds(190, 100, 200, 200);
        usernametext.setBounds(250, 160, 100, 20);
        passwordtext.setBounds(250, 190, 100, 20);
        login.setBounds(250, 250, 80, 50);




        //设置默认按钮
        getRootPane().setDefaultButton(login);








        setSize(600, 400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);


    }

    public static void main(String[] args) {
        new LoginView();
    }

    public JTextField getUsernametext() {
        return usernametext;
    }



    public JPasswordField getPasswordtext() {
        return passwordtext;


    }
}



public class MainView extends JFrame {
    JButton J1 = new JButton("增加");
    JButton J2 = new JButton("修改");
    JButton J3 = new JButton("删除");
    JButton J4 = new JButton("搜索");
    JButton J5 = new JButton("上一页");
    JButton J6 = new JButton("下一页");
    JTextField J7 = new JTextField();



    MainViewTable mainViewTable = new MainViewTable();
    private int pageNow = 1; //当前是第几页
    private int pageSize = 10; //一页显示多少条






    public MainView() {
        super("主界面");
        Container Z = getContentPane();



        layoutCenter(Z);






       setLayout(null);
        //边框颜色
        J7.setBorder(javax.swing.BorderFactory.createLineBorder((new java.awt.Color(0, 0, 0))));
        Z.add(J1);
        Z.add(J2);
        Z.add(J3);
        Z.add(J4);
        Z.add(J5);
        Z.add(J6);
        Z.add(J7);



        J1.setBounds(0,0,100,30);
        J2.setBounds(100,0,100,30);
        J3.setBounds(200,0,100,30);
        J7.setBounds(300,0,180,30);
        J5.setBounds(580,0,100,30);
        J6.setBounds(680,0,100,30);
        J4.setBounds(480,0,100,30);





        //根据屏幕大小设置主界面




        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
        setSize(1000, 1000);
        setLocationRelativeTo(null);
    }

    private void layoutCenter(Container Z) {

        StudentService studentService = new StudentServiceImpl();
        StudentRequest request = new StudentRequest();
        request.setPageNow(pageNow);
        request.setPageSize(pageSize);
        request.setSearchKey(J7.getText().trim());
        TableDTO tableDTO = studentService.retrieveStudents(request);
        Vector<Vector<Object>> data = tableDTO.getData();


        MainViewTableModel mainViewTableModel = MainViewTableModel.assembleModel(data);
        mainViewTable.setDataModel(mainViewTableModel);
        mainViewTable.renderRule();
        JScrollPane JS = new JScrollPane(mainViewTable);
        Z.add(JS);
        JS.setBounds(0,30,1000,970);


    }

    public static void main(String[] args) {new MainView(); }
}


public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSl=false";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String USER_NAME = "root";
    private static final String PWD = "lpb666666";

    static {
        try {
            //com.mysql.jdbc.Driver静态代码块
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
  //获取数据库连接
    public static Connection getConn() {
        try {
            return DriverManager.getConnection(URL, USER_NAME, PWD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static void closeConn(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void closePs(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void closeRs(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}




public class DimensionUtil {

    public static Rectangle getBounds() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        //保证主界面不会覆盖任务栏
        Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(new JFrame().getGraphicsConfiguration());
       Rectangle rectangle =  new Rectangle(screenInsets.left,screenInsets.top,
                screenSize.width-screenInsets.left-screenInsets.right,
                screenSize.height-screenInsets.top-screenInsets.bottom);
        return rectangle;
    }
}



img

img

img

  • 写回答

2条回答 默认 最新

  • pzzhao 2022-11-29 19:38
    关注

    数据库时区问题,可以参考这个 博客 https://blog.51cto.com/jincheng/1913062

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月7日
  • 已采纳回答 11月29日
  • 创建了问题 11月29日

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀