Home > Software design >  How to store and retrieve database information based on logged in user in Java, using swing GUI (Net
How to store and retrieve database information based on logged in user in Java, using swing GUI (Net

Time:12-30

I'm pretty new to Java. I'm using Swing and Netbeans on MySQL DB. I am working on a desktop application that allows users to make orders for products. The user have to sign in to order. How do I save the order information for each user after they have logged in. My login code is as shown.

Database connection (dbconnect.java)

package dbconnect;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

/**
 *
 * @author Nipun Senarath
 */
public class dbconnect {
    
     public static Connection connect()
    {
        Connection sos = null;
        
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            sos = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant","root","");
        } catch (Exception e) 
        {
            JOptionPane.showMessageDialog(null, e);
        }
        return sos;
    }

    public static Connection Connect() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

The login page PatronLogin.java

package patron.auth;


import dbconnect.dbconnect;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import patron.main.MainClass;


public class PatronLogin extends javax.swing.JFrame {
    
    public PatronLogin() {
        initComponents();
    }

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here: Login button
        String uname = jTextField1.getText();
        String pword = jPasswordField1.getText();
        
        if (uname.equals("")||pword.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Some fields are empty", "Error", 1);
        } else {
            try {
                Connection con = dbconnect.connect();
                PreparedStatement pst = con.prepareStatement("select * from patron where username=? and password=?");
                pst.setString(1, uname);
                pst.setString(2, pword);
                ResultSet rs = pst.executeQuery();
                                
                if (rs.next()) {
                    MainClass pt = new MainClass();
                    pt.setVisible(true);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Username or Password do not match record", "Login error", 1);
                } 
            } catch (Exception ex) {
                System.out.println("" ex);
            }
        }
    }        

    public static void main(String args[]) { 
      /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PatronLogin ln = new PatronLogin();
                ln.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                ln.setVisible(true);
            }
        });
    }              

Then the user account page

package patron.main;

import patron.event.EventMenuSelected;
import patron.form.Form_1;
import patron.form.Form_4;
import patron.form.Form_3;
import patron.form.Form_2;
import patron.form.Form_Home;
import java.awt.Color;
import javax.swing.JComponent;

public class MainClass extends javax.swing.JFrame {

    /**
     * Creates new form MainClass
     */
    private Form_Home home;
    private Form_1 form1;
    private Form_2 form2;
    public static Form_3 form3;
    private Form_4 form4;

    public MainClass() {
        initComponents();
        setBackground(new Color(0, 0, 0, 0));
        home = new Form_Home();
        form1 = new Form_1();
        form2 = new Form_2();
        form3 = new Form_3();
        form4 = new Form_4();
        menu.initMoving(MainClass.this);
        menu.addEventMenuSelected(new EventMenuSelected() {
            @Override
            public void selected(int index) {
                if (index == 0) {
                    setForm(home);
                } else if (index == 1) {
                    setForm(form1);
                } else if (index == 2) {
                    setForm(form2);
                } else if (index == 3) {
                    setForm(form3);
                } else if (index == 4) {
                    setForm(form4);
                }
            }
        });
        //  set when system open start with home form
        setForm(new Form_Home());
    }

    public void setForm(JComponent com) {
        mainPanel.removeAll();
        mainPanel.add(com);
        mainPanel.repaint();
        mainPanel.revalidate();
    }
public static void main(String args[]) {      

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainClass().setVisible(true);
            }
        });
    }

I want to insert an order into the order table with order_id, item, price, and patron_id for the logged in user, so I can be able to retieve it in another table showing the particular user's order history, how do I achieve that. Same goes for other patrons...

CodePudding user response:

There's a lot of work to do, but you can "offload" a lot of that. ;-)

If your desktop-application is a "single-user" application you can create a "Singleton" object to store the current logged user.

That object will represent a "Session", that will be built after a successful login and it will contain the logged user (aka Principal).

There'are various points where you can improve:

  • security: password are stored in plain text, it would be better to use an hash function for that -- https://www.baeldung.com/java-password-hashing
  • logic and db code in UI: mixing all the code together will make it very harder to handle it and fix it (believe me). Again, following an Object-Oriented approach is better to model with something like:
interface Products {

  List<Product> listAll();

} 

interface Orders {
  void save(Order order)
}

The implementation of that interfaces will interact with the db, returning the data to the UI and doing the actions started from the user.

  • Related