简体   繁体   English

登录仅适用于数据库中的最后一个用户

[英]Login works only for last user in the database

For some reason the login only works for the last user in the database. 由于某种原因,该登录仅适用于数据库中的最后一个用户。 I have a while loop, but I think it makes the program to go to the last user. 我有一个while循环,但是我认为它使程序转到最后一个用户。 I tried using if statement but then only the first user can log in. 我尝试使用if语句,但是只有第一个用户可以登录。

  if (username!=null && password!=null) {
    pagename = "main";
    } else {
    username = request.getParameter("username");
    password = request.getParameter("password");

            while(results.next()) 
            { 
            if(results.getString(2).equals(password) && results.getString(1).equals(username)) 
            { 
            pagename="main";
            } 
            else 
            { 
            pagename="start";
            } 
    }
  }

How is this caused and how can I solve it? 这是怎么引起的,我该如何解决?

You are copying the entire DB table into Java's memory and doing the comparison in a while loop over all records. 您将整个数据库表复制到Java的内存中,并在while循环中对所有记录进行比较。 You are not aborting the while loop when there's a match with a record, so it continues looping over the remaining records and so the pagename get overridden with "start" everytime. 当与一条记录匹配时,您不会中断while循环,因此它将继续循环其余记录,因此每次使用“ start”覆盖pagename

You need to add a break statement: 您需要添加一个break语句:

if (results.getString(2).equals(password) && results.getString(1).equals(username)) { 
    pagename="main";
    break;
}

Or, better, let SQL do the job it is designed for, selecting and returning exactly the data you need: 或者,更好的方法是让SQL执行它专为设计的工作, 准确选择并返回所需的数据:

preparedStatement = connection.prepareStatement("SELECT id FROM user WHERE username=? AND password=MD5(?)");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();

if (resultSet.next()) {
    pagename = "main";
}
else {
    pagename = "start";
}

That's more efficient and sensible. 这样更有效,更明智。

Why would you loop through the whole table to do this? 您为什么要遍历整个表格来执行此操作? What if you have 1000000 records? 如果您有1000000条记录怎么办? You should query the database with WHERE clause passing the username and password parameters and then simply check if there are returned row or not. 您应该使用传递用户名和密码参数的WHERE子句查询数据库,然后简单地检查是否存在返回的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM