Getting null values in student.java method “studen

2019-09-20 03:04发布

问题:

student.java

import java.io.*;

public class Student implements Serializable  {

    String name;
    String id1,phone,clas;

    public Student() {    
    }

    public String showStudent() {
        return  "Name: "+name+" Address: "+clas+" Phone: "+phone+" ID: "+id1;
    }

    public void Student1(String  id,String n,String c,String ph) {
        name=n;
        id1=id;
        phone=ph;
        clas=c;
    }
}

StudentDAO.java

import java.sql.*; 
import java.io.*;

public class StudentDAO implements Serializable {

    static  String id,detailsi,nam,ph,clas,i;

    public void searchinfo(String id2) {
        id=id2;
        try {
            String url="jdbc:ucanaccess://C:\\Users\\Asim Iqbal\\Documents\\IT.accdb";
            Connection conn = DriverManager.getConnection(url);
            String sql= "SELECT * FROM Student WHERE ID=?";
            PreparedStatement  stmt = conn.prepareStatement(sql);
            stmt.setString(1,id);
            ResultSet rs=stmt.executeQuery();
            if (rs.next()) {
                i=rs.getString("ID");
                nam=rs.getString("Name"); 
                clas=rs.getString("Class");
                ph=rs.getString("Phone");
                Student studentinfo=new Student();
                studentinfo.Student1(i, nam, clas, ph);
            }
        } catch (SQLException e) {
        }
    } 
}

second.jsp

<html> 
    <body>
        <% 
            String id =request.getParameter("ID1");
            StudentDAO std=new StudentDAO();
            Student st=new Student();
            std.searchinfo("id");
        %>
        <h1> <%=st.showStudent()%> </h1>
    </body>
</html>

Getting null values in student.java method "student1()" from studentDAO.java?? StudentDAO.java connects DB properly and give result properly as individually.. But not passing values as a parameter to "student1()" in Student.java file.. Please suggest where i am getting wrong...

回答1:

Change public void searchinfo(String id2) to public Student searchinfo(String id2) and return studentinfo[i.e. Student object].

//JSP corrections

String id = request.getParameter("ID1");
StudentDAO std = new StudentDAO();

Student st = std.searchinfo(id);


回答2:

Issue is because of your creating two instance of student, one in StudentDAO and other second.jsp. Instance created in StudentDAO will contains values.But you are not using that object,Your creating new object in second.jsp value and that object does not contains any values. So your getting null values.

Fix: StudentDAO

public Student searchinfo(String id2) {

. . . .

   Student studentinfo=new Student();
   studentinfo.Student1(i, nam, clas, ph);
return studentinfo;

}

second.jsp

StudentDAO std=new StudentDAO();
Student st= std.searchinfo("id");
<h1> <%=st.showStudent()%> </h1>


标签: java jsp jdbc