我的目标是要求用户输入日期,我的应用程序将检索该日期的所有数据并显示在jsp的表格中。
现在,arraylist返回null,因此它将转到错误页面。 但是在我的数据库中,有。
帮助将不胜感激。 :)
以下是我的代码..
search.jsp
<form method="post" action="SearchServlet">
Date:<input name="rdate">
<input type="submit" value="Search">
</form>
SearchServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String rdate = request.getParameter("rdate");
PersonBean pb = new PersonBean();
pb.setDate(rdate);
PersonDAO pd = new PersonDAO();
ArrayList personarraylist = pd.getDatePerson(pb);
System.out.println(personarraylist);
if (personarraylist.isEmpty() == true) {
response.sendRedirect("error.jsp");
} else {
request.setAttribute("person", rd.getDatePerson(pb));
RequestDispatcher view = request.getRequestDispatcher("success.jsp");
view.forward(request, response);
}
}
PersonDAO
public ArrayList getDatePerson(PersonBean pb) {
ArrayList<PersonBean> listdateperson = new ArrayList<PersonBean>();
String rdate = pb.getDate();
System.out.print(rdate);
int pendingcount = 0;
try {
currentCon = ConnectionManager.getConnection();
Statement statement = currentCon.createStatement();
String count = "SELECT COUNT(*) FROM person where date='" + rdate + "'";
PreparedStatement countstmt = currentCon.prepareStatement(count);
ResultSet countrs = countstmt.executeQuery();
while (countrs.next()) {
pendingcount = countrs.getInt(1);
System.out.print(pendingcount);
}
if (pendingcount == 0) {
PersonBean pbb = null;
pbb.setDate("0");
listdateperson.add(pbb);
}
else {
ResultSet rs = statement.executeQuery("SELECT name, date FROM person WHERE date='" + rdate + "'");
PersonBean pbbb = null;
while (rs.next()) {
PersonBean = new PersonBean();
pbbb.setName(rs.getString("name"));
pbbb.setDate(rs.getString("date"));
}
}
} catch (Exception asd) {
System.out.println(asd.getMessage());
}
return listdateperson;
}
答案 0 :(得分:2)
1)PersonDAO
if
内的代码会引发NullPointerException
if (pendingcount == 0) {
PersonBean pbb = null; //assign null reference
pbb.setDate("0"); //setting value to null reference throws NPE
listdateperson.add(pbb);
}
2)缺少分配对象引用
PersonBean pbbb = null;
while (rs.next()) {
PersonBean = new PersonBean(); //how can you assign object reference to class PersonBean?
一定是
pbbb = new PersonBean();
您正在使用PreparedStatement,然后使用占位符(?)将参数传递给查询,这将Prevent SQL injection
答案 1 :(得分:0)
因为pbbb
pendingcount != 0
添加到while循环的数组列表中