简体   繁体   English

如何使用 swing GUI (Netbeans) 根据 Java 中的登录用户存储和检索数据库信息

[英]How to store and retrieve database information based on logged in user in Java, using swing GUI (Netbeans)

I'm pretty new to Java. I'm using Swing and Netbeans on MySQL DB.我是 Java 的新手。我在 MySQL 数据库上使用 Swing 和 Netbeans。 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)数据库连接(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登录页面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.我想在订单表中插入一个订单,其中包含登录用户的 order_id、商品、价格和 patron_id,这样我就可以在另一个显示特定用户订单历史记录的表中检索它,我该如何实现。 Same goes for other patrons...其他顾客也一样。。。

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.如果您的桌面应用程序是“单用户”应用程序,您可以创建一个“单例”object 来存储当前登录的用户。

That object will represent a "Session", that will be built after a successful login and it will contain the logged user (aka Principal). object 将代表一个“会话”,它将在成功登录后构建,并将包含已登录的用户(又名 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安全性:密码以纯文本形式存储,最好使用 hash function -- 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). UI 中的逻辑和数据库代码:将所有代码混合在一起将使处理和修复它变得更加困难(相信我)。 Again, following an Object-Oriented approach is better to model with something like:同样,遵循面向对象的方法比 model 更好,例如:
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.该接口的实现将与数据库交互,将数据返回到 UI 并执行从用户开始的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用NetBeans GUI Builder for Java Swing添加GridLayout? - How to add a GridLayout using NetBeans GUI Builder for Java Swing? 如何将用户从GUI提供的输入存储到Java中的字符串数组? 我正在使用Java swing创建GUI - How can I store inputs given by the user from GUI to a string array in java? I am using java swing to create the GUI 如何在基于Swing或NetBeans平台的Java GUI应用程序中更改WM_CLASS值? - How to alter WM_CLASS value in a Java GUI application based on Swing or NetBeans Platform? NetBeans 平台:如何以编程方式设置基于 Swing 的 GUI 组件的样式? - NetBeans Platform: How to style the Swing based GUI components programmatically? 使用Java Swing和Netbeans IDE创建GUI - Creating GUI's using Java Swing with Netbeans IDE 如何将通过Java Swing GUI输入的用户信息输出到Excel工作表? - How can I output a user's information entered through a Java Swing GUI onto an excel sheet? 如何在Java Swing Gui中从用户输入存储变量以备将来使用? - How to store variables for further use from User-input in Java Swing Gui? 如何使用Netbeans GUI编辑器创建Swing选项卡式窗格应用程序 - How to create swing Tabbed Pane application using the Netbeans GUI editor Java 中的 GUI 使用 Swing - GUI in Java using Swing 在 java 中使用 swing GUI - Using swing GUI in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM