문제

My goal is ask the user to enter a date and my application will retrieve all the data from that date and display in a table in jsp.

Right now, the arraylist returns be null, thus it will go to error page. however inside my database, there is.

Help will be appreciate. :)

Below are my codes..

At search.jsp

<form method="post" action="SearchServlet">
Date:<input name="rdate">
<input type="submit" value="Search">
</form>

At 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);
}
}

At 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) Code in PersonDAO inside if throws NullPointerException

if (pendingcount == 0) {
 PersonBean pbb = null;  //assign null reference
 pbb.setDate("0");  //setting value to null reference throws NPE
 listdateperson.add(pbb);
}

2) Missing to assign object reference

PersonBean pbbb = null; 
while (rs.next()) {
 PersonBean = new PersonBean(); //how can you assign object reference to class PersonBean?

It must be

pbbb = new PersonBean();

You are using PreparedStatement, then use place holder(?) for passing the parameter to query, this will Prevent SQL injection

See also

다른 팁

Because you didn't add the pbbb into the array list in the while loop when pendingcount != 0

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top