简体   繁体   中英

Java. Login not working

I am creating a management system in java.

I have this login form. The connection to database seems fine as it didn't give error on that.

But when I try to do try {} and catch {}, it gives an error.

I hope if any one can help me.

It gives this always:

catch (Exception ex) { JOptionPane.showMessageDialog(null, "Error on login operation", "Login Error", JOptionPane.ERROR_MESSAGE); }

public class Login extends javax.swing.JFrame {


        private Connection con;
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();


public Login() {
    super("System Login");
    initComponents();


    this.setResizable(false);
    this.setLocation((screen.width - 500) / 2, ((screen.height - 350) / 2));
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    comcateg.addItem("Manager");
    comcateg.addItem("Clerk");

    ButtonListener listener = new ButtonListener();
    btlogin.addActionListener(listener);
    btcancel.addActionListener(listener); 
    con = DBConnection.getDBConnection();
    if (con == null) {
        JOptionPane.showMessageDialog(null, "Error on establishing database connection", "Error", JOptionPane.ERROR_MESSAGE);
        this.dispose();
    }
    }

public void log(){

    String user = txtuser.getText();
    String pw = txtpw.getText();
    String cat = comcateg.getSelectedItem().toString();
    String SQL;
    SQL = "SELECT * FROM AAP.USERS WHERE user_id='" + user + "' AND pword='" + pw +"' AND categ='" + cat +"'";

    **try{

        Statement stmt = con.createStatement();
        stmt.execute(SQL);
        ResultSet rs = stmt.getResultSet();
        boolean recordfound = rs.next();
        if (recordfound) {
            LoadMainWindow();                
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "The system could not log you in.\n" +
                    " Please make sure your username and password are correct", "Login Failure", JOptionPane.INFORMATION_MESSAGE);
            txtuser.setText("");
            txtpw.setText("");
            txtuser.requestFocus();
        }
    } 
    catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error on login operation", "Login Error", JOptionPane.ERROR_MESSAGE);
    }


}**
public void LoadMainWindow() {
    if (comcateg.getSelectedItem().equals("Manager")) {
        new MainWindow().LoginManager();            
    } else {
        new MainWindow().LoginClerk();
    }
    }

private class ButtonListener implements ActionListener {


    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btlogin) {
            if (txtuser.getText() == null || txtuser.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Enter username", "Missing field", JOptionPane.DEFAULT_OPTION);
                txtuser.requestFocus();
                return;
            }
            if (txtpw.getText() == null || txtpw.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Enter password", "Missing field", JOptionPane.DEFAULT_OPTION);
                txtpw.requestFocus();
                return;
            }
            log();
        } else if (e.getSource() == btcancel) {
            System.exit(0);
        }//if else closed
    }//actionPerformed() closed
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    userid = new javax.swing.JLabel();
    pword = new javax.swing.JLabel();
    categ = new javax.swing.JLabel();
    txtuser = new javax.swing.JTextField();
    txtpw = new javax.swing.JTextField();
    comcateg = new javax.swing.JComboBox();
    btlogin = new javax.swing.JButton();
    btcancel = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    userid.setText("User ID:");

    pword.setText("Password:");

    categ.setText("Category:");

    txtuser.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtuserActionPerformed(evt);
        }
    });

    txtpw.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtpwActionPerformed(evt);
        }
    });

    comcateg.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
    comcateg.setToolTipText("");
    comcateg.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            comcategActionPerformed(evt);
        }
    });

    btlogin.setText("Login");
    btlogin.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btloginActionPerformed(evt);
        }
    });

    btcancel.setText("Cancel");
    btcancel.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btcancelActionPerformed(evt);
        }
    });

    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(jPanel1Layout.createSequentialGroup()
            .add(40, 40, 40)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(btlogin)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(btcancel))
                .add(jPanel1Layout.createSequentialGroup()
                    .add(categ)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                    .add(comcateg, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .add(jPanel1Layout.createSequentialGroup()
                    .add(pword)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(txtpw))
                .add(jPanel1Layout.createSequentialGroup()
                    .add(userid)
                    .add(18, 18, 18)
                    .add(txtuser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(64, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(jPanel1Layout.createSequentialGroup()
            .add(48, 48, 48)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(userid)
                .add(txtuser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(pword)
                .add(txtpw, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(categ)
                .add(comcateg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(18, 18, 18)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(btlogin)
                .add(btcancel))
            .addContainerGap(48, Short.MAX_VALUE))
    );

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void txtuserActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
}                                       

private void txtpwActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
}                                     

private void btloginActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
}                                       

private void btcancelActionPerformed(java.awt.event.ActionEvent evt) {                                         
  // TODO add your handling code here:
}                                        

private void comcategActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Login().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton btcancel;
private javax.swing.JButton btlogin;
private javax.swing.JLabel categ;
private javax.swing.JComboBox comcateg;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel pword;
private javax.swing.JTextField txtpw;
private javax.swing.JTextField txtuser;
private javax.swing.JLabel userid;
// End of variables declaration                   

}

The DBConnect class code:

public class DBConnection {

public static Connection getDBConnection() {
    Connection connection;
    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        connection = DriverManager.getConnection("jdbc:derby:Ambulance;create=true");
        return connection;
    } catch (Exception ex) {
        return null;
    }
}
}

The exception I get is this:

run: java.sql.SQLSyntaxErrorException: Schema 'AAP' does not exist at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source) at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source) at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) at Login.log(Login.java:56) at Login$ButtonListener.actionPerformed(Login.java:99) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButton Model.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6505) at javax.swing.JComponent.processMouseEvent(JComponent.java:3321) at java.awt.Component.processEvent(Component.java:6270) at java.awt.Container.processEvent(Container.java:2229) at java.awt.Component.dispatchEventImpl(Component.java:4861) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) at java.awt.Container.dispatchEventImpl(Container.java:2273) at java.awt.Window.dispatchEventImpl(Window.java:2719) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.E ventQueue.dispatchEventImpl(EventQueue.java:729) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue$4.run(EventQueue.java:702) at java.awt.EventQueue$4.run(EventQueue.java:700) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:699) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at j ava.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

I think the query is not getting executed properly because the schema AAP doesn't exists and you are accessing the table users "SELECT * FROM AAP.USERS... "and it is getting Exception at line 41 stmt.execute(SQL);

Because of which it is going in the catch block.

In

SQL = "SELECT * FROM AAP.USERS WHERE user_id='" + user + "' AND pword='" + pw 
+"' AND categ='" + cat +"'";

Your AAP table does not exist, you need to be sure it has been created before you query it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM