[英]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.