Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从objectInputStream接收对象并将该对象传递给方法_Java_Object_Objectinputstream - Fatal编程技术网

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

Java 如何从objectInputStream接收对象并将该对象传递给方法,java,object,objectinputstream,Java,Object,Objectinputstream,我被困在一个大学作业的问题上,我需要一些帮助。我们必须创建一个服务器客户端程序,该程序有一个带有基本表单的UI来输入数据,当单击register按钮时,表单将创建StudentDetails类的对象并将其发送到服务器类。服务器类必须接收StudentDetails对象并将该对象传递给toDatabase类。toDatabase类必须接受StudentDetails对象并将数据输入数据库 我已经做了几个小时的研究,但我只能找到如何将objectInputStream中的对象写入文件 学生资料课 p

我被困在一个大学作业的问题上,我需要一些帮助。我们必须创建一个服务器客户端程序,该程序有一个带有基本表单的UI来输入数据,当单击register按钮时,表单将创建StudentDetails类的对象并将其发送到服务器类。服务器类必须接收StudentDetails对象并将该对象传递给toDatabase类。toDatabase类必须接受StudentDetails对象并将数据输入数据库

我已经做了几个小时的研究,但我只能找到如何将objectInputStream中的对象写入文件

学生资料课

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();

}
}

我希望结果是将数据插入到数据库中

您希望将对象插入到数据库中,但会发生什么?我看这里没有错误。API会让您困惑吗?我不知道如何将objectInput流接收到的对象传递给toDatabase()方法,因为需要插入数据库的数据存储在studentDetails对象中。首先,您需要至少调用该方法一次。大概是在你收到物品后。第二,该方法必须声明为接受参数(目前它不接受参数)。您能否演示如何以代码形式将该对象传递给toDatabase对象。我已经编辑了调用toDatabase方法的main方法,因为您已经编辑了该方法,所以您的代码不再编译,对吗?您似乎需要一个Java教程,向您解释该语言的主要概念。但是,StackOverflow不提供教程,您需要在其他地方搜索这些教程。