Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle no entity in database for entered parameters?
    text
    copied!<p>I am trying to implement simple login system. I have a JSP with form where user enters username and password, and then servlet that is reading those parameters. You'll understand from servlet code:</p> <pre><code>User user = userDao.findUserWithUsernameAndPassword(username, password); // user found if (user!=null) { session = request.getSession(true); session.setAttribute("user", user); loginMessage = "Welcome"; request.setAttribute("loginMessage", loginMessage); RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } else // username and password not matching { loginMessage = "Wrong username or password! Please try again."; request.setAttribute("loginMessage", loginMessage); RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } </code></pre> <p>This works if I enter valid username and password, but if not I am getting next exception: </p> <pre><code>javax.persistence.NoResultException: Query "SELECT u FROM User u WHERE u.username like :username AND u.password LIKE :password" selected no result, but expected unique result. </code></pre> <p>What is the proper way of handling this situation? I would like for wrong username and password parameters to display appropriate message (forwarding in 'loginMessage' variable).</p> <p>[added]This is the code in UserDAOBean:</p> <pre><code>@Stateless @Local(UserDAOLocal.class) @TransactionManagement(TransactionManagementType.CONTAINER) @TransactionAttribute(TransactionAttributeType.REQUIRED) public class UserDAOBean extends GenericDAOBean&lt;User, Integer&gt; implements UserDAOLocal{ public User findUserWithUsernameAndPassword(String username, String password) { Query q = em.createNamedQuery("findUserWithUsernameAndPassword"); q.setParameter("username", username); q.setParameter("password", password); User result = (User) q.getSingleResult(); return result; } } </code></pre> <p>And named query in entity User is:</p> <blockquote> <p>@NamedQuery(name = "findUserWithUsernameAndPassword", query = "SELECT u FROM User u WHERE u.username like :username AND u.password LIKE :password")</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload