我的目标是要求用户输入日期,我的应用程序将检索该日期中的所有数据并显示在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;
}
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,然后使用占位符(?)来将参数传递给查询,这将防止SQL注入
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句