1

In below snippet, the else is always invoked. The if is never entered, even though the while block is successfully entered.

while (rs.next()) {

     username = rs.getString(2);
     password = rs.getString(3);

}
if(rs.next())
{
   response.sendRedirect("Welcome.jsp");

}        
else {
  response.sendRedirect("Fail.jsp");
}

How is this caused and how can I solve it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Aziz
  • 129
  • 1
  • 9
  • And what is the problem? – jdabrowski Mar 08 '16 at 15:00
  • I put right username and password and i got redirected to fail.jsp instead of welcome.jsp – Aziz Mar 08 '16 at 15:03
  • This is dangerous code. You open a connection in the `init()` method and never close it. Connections are typically obtained and returned within a request/response – lance-java Mar 08 '16 at 15:04
  • Yes it is , how to close it ? I thin it would be better if i create a DBConnection java class instead of putting it with the servlet class – Aziz Mar 08 '16 at 15:05
  • Please learn how to ask focused questions. This is again not a JSP/Servlet related problem. I clarified the question. As to the dangerously threadunsafe JDBC connection management in your initial snippet, head to http://stackoverflow.com/q/9428573 (and in the meanwhile also http://stackoverflow.com/q/3106452) – BalusC Mar 08 '16 at 15:05
  • 2
    You loop until `rs.next()` returns false and thus should return false in the if-condition as well, why should it enter the block then? I guess what you actually want is to check whether the loop executed at least once, e.g. by checking `username != null`. – Thomas Mar 08 '16 at 15:05
  • @BalusC Sorry , thanks for feeding back – Aziz Mar 08 '16 at 15:06

2 Answers2

1

What you possibly wanted:

if(rs.next()) {
    username = rs.getString(2);
    password = rs.getString(3);
    response.sendRedirect("Welcome.jsp");
} else {
    response.sendRedirect("Fail.jsp");
}
blafasel
  • 1,091
  • 14
  • 25
0

Have a look at the documentation of next() method of resultset here.

When a call to the next method returns false, the cursor is positioned after the last row.

So, when control comes out of while loop, cursor has already reached the position after the last row and hence, rs.next() will never return true. I wold like to suggest a couple of changes:

  • Add a flag in the while loop which is set to true of control enters inside while loop and then check for that flag, e.g.:

    boolean exists = false; while(rs.next(){ exists = true; //other logic } if(exists){ response.sendRedirect("Welcome.jsp"); }

  • Add proper exception handling in the code.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102