繁体   English   中英

如何修复NullPointerException

[英]How to fix NullPointerException

我正在写Java servlet ,它应该通过user_id获得DVD。 但是我对NullPointerException有问题。 有人知道如何解决吗? 当我尝试通过if (nickname != null )修复它时, request.setAttribute("dvds", dvds);属性dvds出现问题request.setAttribute("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;
}

假设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);

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

由于请求缺少参数(或者拼写错误或其他原因),因此您似乎正在获得NPE。 在发送请求的过程中,这绝对是一个错误。

正确的解决方案是:

  • 发送某种如果错误响应getParameter("nickname")返回null

  • 修复发送缺少参数的请求的Web表单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM