当前位置: 代码迷 >> J2EE >> 关于java.lang.NullPointerException,该怎么解决
  详细解决方案

关于java.lang.NullPointerException,该怎么解决

热度:16   发布时间:2016-04-22 01:42:54.0
关于java.lang.NullPointerException
我是看一本书里面的代码照着来的,结果出现这个错误.......求高手帮忙解决

java.lang.NullPointerException
com.dt.daoImpl.UserDAOImpl.findUserByUserName(UserDAOImpl.java:92)
com.dt.servlet.Login.doGet(Login.java:34)
com.dt.servlet.Login.doPost(Login.java:55)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

findUserByUserName//
Java code
    public User findUserByUserName(String userName) {        // TODO Auto-generated method stub        Connection conn = DBConnection.getConnection();    //获得连接对象        String findByUserNameSQL = "select * from user where username=?";        PreparedStatement pstmt = null;        ResultSet rs = null;        User user = new User();        try{            pstmt = conn.prepareStatement(findByUserNameSQL);            pstmt.setString(1,userName);            rs = pstmt.executeQuery();            if(rs.next()){                user = new User();                user.setUserID(rs.getInt(1));                user.setUserName(rs.getString(2));                user.setPassword(rs.getString(3));            }        }catch(SQLException e){                e.printStackTrace();        }finally{            DBConnection.close(rs);            DBConnection.close(pstmt);            DBConnection.close(conn);        }                return user;    }


Java code
            if(password == null || "".equals(password)){                request.setAttribute("error", "请输入密码");            //判断是否输入密码                dispatcher = servletContext.getRequestDispatcher("/admin/index.jsp");            }else{                UserDAO userDAO = UserDAOFactory.getUserDAOInstance();                        //获得DAO实现类实例                User user = userDAO.findUserByUserName(userName);//查询账号                if(user == null){                    request.setAttribute("error", "该账户不存在");                    dispatcher = servletContext.getRequestDispatcher("/admin/index.jsp");                }else{                    if(password.equals(user.getPassword())){                        request.getSession().setAttribute("user", user);        //该账户信息保存                        response.sendRedirect("admin.jsp");                        return ;                    }else{                        request.setAttribute("error", "密码不正确!");                        dispatcher = servletContext.getRequestDispatcher("/admin/index.jsp");                    }                }            }


------解决方案--------------------
findUserByUserName(UserDAOImpl.java:92)
看92行
------解决方案--------------------
探讨
com.dt.daoImpl.UserDAOImpl.findUserByUserName(UserDAOImpl.java:92)

------解决方案--------------------
如果 conn 是空的话,证明得到 conn 的那个类有问题,你把那个 conn 打出来看一下,如果是个字符串,证明 conn 有值 ,如果是 null, 证明 DBConnection.getConnection() 有问题,要去那里面改的。。
  相关解决方案