Is there any better way to handle Exceptions using Play framework apart from what am using?
Query q = JPA.em().createQuery("SELECT u FROM " +
User.class.getName() +
" u WHERE userCode = :userCd AND password = :password"
)
.setParameter("userCd", userName)
.setParameter("password", password);
User user=null;
try {
user = (User) q.getSingleResult();
} catch (NoResultException n) {
flash.put("username",userName);
flash.error("Invalid Credentials");
index();
}
What I am trying to achieve is so simple, User validation. As of now the above code works properly but wanted to know from anyone to assist me if there is any better way to handle Exceptions in Play apart from this?
Part 8 of the play framework getting started guide covers off how to set up a a user login within the play framework. There is a lot of framework already built to handle this so you just need to figure out how to make use of it.
Have a look at the simplified query stuff in the play documentation for more info on how to do queries using the play framework rather than resorting to straight JPA.
Answering your specific question, you have a few options…
Option 1 (pass the username and password into the query):
Option 2 (pass only username and then check password):
Option 2 has some benefits around how you store the password etc. So you might have it salted and hashed. Or perhaps you want to lock the account after 5 attempts on it, in this scenario you need to get the user object whether or not the password matches.