如何从objectInputStream接收对象并将该对象传递给方法

时间:2019-10-17 14:41:46

标签: java object objectinputstream

我遇到了大学分配的问题,需要一些帮助。我们必须创建一个服务器-客户端程序,该程序具有一个带有基本表单的UI来输入数据,单击注册按钮后,该表单将创建StudentDetails类的对象并将其发送到服务器类。服务器类必须接收StudentDetails对象,并将该对象传递给toDatabase类。 toDatabase类必须接受StudentDetails对象,并将数据输入数据库中

我已经进行了数小时的研究,但我只能找出如何将对象从objectInputStream写入文件

StudentDetails类

public class StudentDetails implements Serializable{
private String studentID;
private String firstName;
private String lastName;
private String contactNum;
private String address;

//constructor
public StudentDetails(String studentID, String firstName, String lastName, String contactNum, String address) {
    this.studentID = studentID;
    this.firstName = firstName;
    this.lastName = lastName;
    this.contactNum = contactNum;
    this.address = address;
}
//getter for studentID
public String getStudentID(){
    return studentID;
}
//getter for firstName
public String getFirstName(){
    return firstName;
}
//getter for lastName
public String getLastName(){
    return lastName;
}
//getter for contactNum
public String getContactNum(){
    return contactNum;
}
//getter for address
public String getAddress(){
    return address;
}
}

客户端类

public class Client extends javax.swing.JPanel {
//declaring the GUI components
private javax.swing.JFrame jFrameMain;
private javax.swing.JPanel jPanelMain;
private javax.swing.JLabel lblStudentID;
private javax.swing.JLabel lblFirstName;
private javax.swing.JLabel lblLastName;
private javax.swing.JLabel lblContactNum;
private javax.swing.JLabel lblAddress;
private javax.swing.JTextField txfStudentID;
private javax.swing.JTextField txfFirstName;
private javax.swing.JTextField txfLastName;
private javax.swing.JTextField txfContactNum;
private javax.swing.JTextField txfAddress;
private javax.swing.JButton btnRegister;
GridLayout grid = new GridLayout(6, 2);

public Client() throws IOException{
    createForm();
}

private void createForm() throws IOException{

    jFrameMain = new javax.swing.JFrame();
    jPanelMain = new javax.swing.JPanel();
    txfStudentID = new javax.swing.JTextField();
    txfFirstName = new javax.swing.JTextField();
    txfLastName = new javax.swing.JTextField();
    txfContactNum = new javax.swing.JTextField();
    txfAddress = new javax.swing.JTextField();
    lblStudentID = new javax.swing.JLabel();
    lblFirstName = new javax.swing.JLabel();
    lblLastName = new javax.swing.JLabel();
    lblContactNum = new javax.swing.JLabel();
    lblAddress = new javax.swing.JLabel();
    btnRegister = new javax.swing.JButton();

    //sets the panel to grid layout
    jPanelMain.setLayout(grid);

    //sets the lable text
    lblStudentID.setText("Student ID:");
    lblFirstName.setText("First Name:");
    lblLastName.setText("Last Name:");
    lblContactNum.setText("Contact Number:");
    lblAddress.setText("Address:");

    //sets the textfield text
    txfStudentID.setText("");
    txfFirstName.setText("");
    txfLastName.setText("");
    txfContactNum.setText("");
    txfAddress.setText("");

    //sets the button text
    btnRegister.setText("Register");

    //sets the JFrame size
    jFrameMain.setSize(300, 250);

    //sets the JFrames location
    jFrameMain.setLocationRelativeTo(null);

    //adds the panel to the frame
    jFrameMain.add(jPanelMain);

    //adds the first rows components
    jPanelMain.add(lblStudentID);
    jPanelMain.add(txfStudentID);

    //adds the second rows components
    jPanelMain.add(lblFirstName);
    jPanelMain.add(txfFirstName);

    //adds the third rows components
    jPanelMain.add(lblLastName);
    jPanelMain.add(txfLastName);

    //adds the forth rows components
    jPanelMain.add(lblContactNum);
    jPanelMain.add(txfContactNum);

    //adds the fifth rows components
    jPanelMain.add(lblAddress);
    jPanelMain.add(txfAddress);

    //adds the last rows components
    jPanelMain.add("", this);//leves the grid empty
    jPanelMain.add(btnRegister);

    //button action listener
    btnRegister.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //vairiables to store the data from the textfield and trims the data 
            String studentID = txfStudentID.getText().trim();
            String firstName = txfFirstName.getText().trim();
            String lastName = txfLastName.getText().trim();
            String contactNum = txfContactNum.getText().trim();
            String address = txfAddress.getText().trim();

            //if tests that the textfields cannot be empty
            if(studentID.isEmpty()){
                JOptionPane.showMessageDialog(jPanelMain, "Student ID cannot be empty");
            }
            else if(firstName.isEmpty()){
                JOptionPane.showMessageDialog(jPanelMain, "First name cannot be empty");
            }
            else if(lastName.isEmpty()){
                JOptionPane.showMessageDialog(jPanelMain, "Last Name cannot");
            }
            else if(contactNum.isEmpty()){
                JOptionPane.showMessageDialog(jPanelMain, "Contact number cannot be empty");
            }
            else if(address.isEmpty()){
                JOptionPane.showMessageDialog(jPanelMain, "Address cannot be empty");
            }
            else{
                try{

                    //apptempt connection to server
                    Socket socket = new Socket("localhost",7777);

                    //Creates an output Stream
                    ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());

                    //creates an object of the studentDetails
                    StudentDetails studentDetails = new StudentDetails(studentID, firstName, lastName, contactNum, address);

                    //sends the studentDetails object to the server
                    toServer.writeObject(studentDetails);
                    JOptionPane.showMessageDialog(jPanelMain, "Success");
                }
                catch (IOException exception){
                    JOptionPane.showMessageDialog(jPanelMain, "Failed to connect to server");
                    exception.printStackTrace();
                }

            }
        }
    });

    //sets the Frame visible
    jFrameMain.setVisible(true);
    jFrameMain.setDefaultCloseOperation(jFrameMain.EXIT_ON_CLOSE);

}


public static void main(String[] args) throws IOException {
    new Client();
}
}

服务器类

public class Server{
private ObjectOutputStream outputClient;
private ObjectInputStream inputClient;
private Object student;

public Server(){
    try{
        //create server socket
        ServerSocket serverSocket = new ServerSocket(7777);
        System.out.println("Server started");

        outputClient = new ObjectOutputStream(new FileOutputStream("student.dat",true));
        while(true){
            //listens for any new connection request
            Socket socket = serverSocket.accept();

            //create an input stream from the socket
            inputClient = new ObjectInputStream(socket.getInputStream());

        }
    }
    //temporaily commented out catch
    //catch(ClassNotFoundException classEx){
        //classEx.printStackTrace();
    //}
    catch(IOException ex){
        ex.printStackTrace();
    }
}

public void toDatabase(){
    try{
        Class.forName("com.mysql.jdbc.Driver");
        //database connection
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pihe2019","root","");

        //mysql insert statment
        String query = " insert into details (studenID, firstName, lastName, contactNum, address)" + " values (?, ?, ?, ?, ?)";

        //sql insert preparedstatment
        PreparedStatement preparedStmt = con.prepareStatement(query);
        preparedStmt.setString(1, "(StudenID from object DATA)");
        preparedStmt.setString(2, "(firstName from object DATA)");
        preparedStmt.setString(3, "(lastName from object DATA)");
        preparedStmt.setString(4, "(contactNum from object DATA)");
        preparedStmt.setString(5, "(address from object DATA)");

        //excute the prepared statment
        preparedStmt.execute();

        con.close();
    }catch(ClassNotFoundException clEx){
      clEx.printStackTrace();
    }
    catch(SQLException sqlEx){
        sqlEx.printStackTrace();
    }
}

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

}
}

我希望结果是插入数据库的数据

0 个答案:

没有答案