日期:2014-05-17  浏览次数:20863 次

错误500 NullPointerException急急急急急急急急急急急急急急急谢谢了先
首先,我估计不单只是这个空指针的问题,因为,程序的键壮性不好。 StudentUser这个类是个bean
public class StudentDao extends BaseDao{

public StudentUser[] getEmpByEmpno() throws SQLException{
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
StudentUser user[] = null; //定义了一个对象数组
try{
conn=ConnectionFactory.getConnection();
String sql="select * from student ";
stmt=conn.prepareStatement(sql);
rs=stmt.executeQuery();
int i = 0;
while(rs.next()){
user[i].setId(rs.getInt(1));
user[i].setName(rs.getString(2));
user[i].setSex(rs.getString(3));
user[i].setCls(rs.getString(4));
i++;
}
return user;




下面这个是个servlet,,,,,,之前还有几个按钮,,主要是 这两个类的问题,我估计
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

StudentDao sd = new StudentDao();
StudentUser su[] = null;
try {
su = sd.getEmpByEmpno();
out.println(su[0].getId());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

,,在页面上运行是500,NullPointerException
控制台上是好多,第一行是
严重: Servlet.service() for servlet SeachStudent threw exception
java.lang.NullPointerException
at com.java.servlet.SeachStudent.doGet(SeachStudent.java:54)






------解决方案--------------------
首先你的user数组没有new,再有这里你为什么要用数组而不用list之类的集合我没有搞明白,因为数组的长度这里你不要确定,如果你非要用数组那么循环内的代码应该改成这样:
Java code

while(rs.next()){
user[i] = new StudentUser();
user[i].setId(rs.getInt(1));
user[i].setName(rs.getString(2));
user[i].setSex(rs.getString(3));
user[i].setCls(rs.getString(4));
i++;
}