如何修复NullPointerException

时间:2014-01-04 10:27:56

标签: java servlets nullpointerexception

我正在编写java servlet,它应该通过user_id获取dvd。但我对NullPointerException有疑问。有没有人知道如何解决它?当我尝试通过if (nickname != null )进行修复时,我在request.setAttribute("dvds", dvds);中遇到了属性dvds的问题,谢谢

List<Dvd> dvds;
    try {
        String nickname = request.getParameter("nickname");
        User user = userDao.getByLogin(nickname);
        Long userId = user.getId();
        dvds = this.dvdDao.getDvdsByUserId(userId);
    } catch (SQLException e) {
        throw new ServletException("Unable to get dvds", e);
    }

    request.setAttribute("dvds", dvds);
    RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/loans.jsp");
    dispatcher.forward(request, response);

}
}   


 public List<Dvd> getDvdsByUserId(Long user_id) throws SQLException {
    List<Dvd> dvds = new ArrayList<Dvd>();
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
        connection = getConnection();
        preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
        preparedStatement.setLong(1, user_id);
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            Dvd dvd = new Dvd();
            dvd.setId(resultSet.getInt("id"));
            dvd.setUser_id(resultSet.getString("user_id"));
            dvd.setName(resultSet.getString("name"));
            dvd.setBorrower(resultSet.getString("borrower"));
            dvd.setMail(resultSet.getString("mail"));
            dvd.setBorrow_date(resultSet.getString("borrow_date"));
            dvd.setBorrow_until(resultSet.getString("borrow_until"));
            dvds.add(dvd);
        }

    } catch (SQLException e) {
        throw e;
    } finally {
        cleanUp(connection, preparedStatement);
    }

    return dvds;
}

2 个答案:

答案 0 :(得分:0)

假设nickname是问题(也考虑到不存在的用户):

List<Dvd> dvds = new ArrayList<Dvd>;
try {
    final String nickname = request.getParameter("nickname");
    if (nickname != null) {
        final User user = this.userDao.getByLogin(nickname);
        if (user != null) {
            dvds = this.dvdDao.getDvdsByUserId(user.getId());
        } else {
            // handle non-existent user
        }
    } else {
        // handle no "nickname" parameter was present
    }
} catch (SQLException e) {
    throw new ServletException("Unable to get dvds", e);
}

request.setAttribute("dvds", dvds);
final RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/loans.jsp");
dispatcher.forward(request, response);

答案 1 :(得分:0)

似乎您的代码在请求中需要“昵称”参数才能正常工作。 (如果您没有“昵称”,则无法找出用户ID,并检索该用户的DVD ...)

您似乎也获得了NPE,因为请求缺少参数(或者拼写错误或其他内容)。在发送请求的任何内容中,这绝对是一个错误

正确的解决方案是:

  • 如果getParameter("nickname")返回null AND

  • ,则会发送某种错误回复
  • 修复发送缺少参数的请求的网络表单。