I have found a few answers to this question on this site, but haven't been able to apply it correctly. I'm trying to take a user's input for user name and password and check it against a database to see if its correct. Everything works fine unless the username entered is not in the database. In that case the query doesn't find any rows. I'm doing this with derby in netbeans. So I think I'm just having trouble detecting when the query is sent with an unknown username. Any Suggestions?
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "MyServlet", urlPatterns ={"/echo"})
public class LoginAction extends HttpServlet {
private ResultSet resultSet;
private Connection con;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
String userName = request.getParameter("username");
String password = request.getParameter("password");
if (userName.length()>0 & password.length()>0){
try{
String url = "jdbc:derby:c:/users/project/.netbeans-derby/";
String db = "loginpass";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String user = "user";
String pass = "pass";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
String statement = "SELECT PASSWORD FROM LOGINPASS WHERE LOGIN = '"+userName+"'";
PreparedStatement prepStatement = con.prepareStatement(statement);
resultSet = prepStatement.executeQuery();
while (resultSet.next()){
if (resultSet.getString("password").equals(password)){
out.println("Login attempt successful!");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
} else {
out.println("Password incorrect");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}
}
con.close();
}catch(Exception e){
out.println("caught...");
e.printStackTrace();
}
} else {
out.println("Login attempt failed");
out.println("<a href='index.jsp'>Back to Login Page</a>");
}
} finally {
out.close();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}