java - List interface not working on my servlet -
i working on login page i'll needing check if user's input valid comparing every item in arraylist input.
here how implemented in servlet
public class userlogin extends httpservlet { protected void processrequest(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); try (printwriter out = response.getwriter()) { string un = request.getparameter("username"); string pw = request.getparameter("password"); userinitializer user = new userinitializer(); user.initializeset(); string status = user.compare(un,pw); system.out.println(status); //only used check if desired output returned. } }
and here implementation of model class
public class userinitializer { public static list<user> users = new arraylist<user>(); public void initializeset() { users.add(new user("user1", "abcd")); users.add(new user("user2", "wxzy")); users.add(new user("user3", "1234")); } public string compare(string u, string p) { iterator<user> iterate = users.iterator(); int stop = 0; string username = null; while (iterate.hasnext() && (stop == 0)) { user user = iterate.next(); if (user.getusername().equals(u)) { if (user.getpassword().equals(p)) { username = u; stop = 1; } } else { username = "invalid"; //username not found } } return username; }}
my user class
class user { private string username, password; public user(string u, string p) { this.username = u; this.password = p; } public void setusername(string u) { this.username = u; } public void setpassword(string p) { this.password = p; } public string getusername() { return username; } public string getpassword() { return username; }}
i've tried working on using plain java project , worked fine when implemented in servlet, compare() method returns "invalid".
i think there's wrong initializeset method. can confirm this?
any appreciated. thanks!
your user
class wrong.
public string getpassword() { return username; }
this method should return password, not user name.
what happens when sees correct username, compares password returned getpassword()
. not password, moves on next user.
the next user not correct, sets user name "invalid".
first thing correct method. also, if matched correct user, always stop loop, whether or not password correct. there no point in continuing match user rest of list.
Comments
Post a Comment