Create Query SQL - Hibernate Java EE

0

I have a small concern and I hope that the most experienced can help me.

I'm doing a web project with the Framework Hibernate , it turns out that I have it connected to a MySQL database in XAMPP, all right, I created a login so that users can log in, this is where my problem is born.

I have created the following method

public Usuarios iniciarSesion(String user, String pass) { try { iniOperacion(); //Abre la sesión con la BD List<Usuarios> listaUsuarios = sesion.createQuery("from Usuarios where nombre_usuario = '" + user + "' and password = '" + pass + "'").list(); for (Usuarios item : listaUsuarios) { return item; } } catch (Exception e) { sesion.close(); throw new RuntimeException("No se ha podido iniciar sesión. Reintente nuevamente."); } return null; }

The method receives the user name and password, then through a SQL query I rescue the users that I find and I save it in a List of type Users, then I go through the list to rescue the user that has those credentials and I return it, in case of I did not find any, I closed the connection with the BD and captured the error. I have the problem when I can not find any user with these credentials, that is, when the user does not exist in the database.

I have a JSP view called login.jsp, and in it the form that goes to Servlet called ServletLogin.java, this driver allows me to redirect to different pages depending on the type of User, in this case there are only two, administrator and Player (is an application to add athletes to the Olympic Games). If the user is an administrator, he redirects it to the path /administrador/index.jsp and otherwise to /jugador/index.jsp . In case you do not find a user or the user's credentials are not correct, what I want is to redirect me again to /login.jsp but since no user can be found in the database, instead of redigating to login.jsp it shows me the following error java.lang.NullPointerException .

I think I'm a bit unclear because this happens, when you get to Query in the iniciarSesion() method, no data is stored in the list, so it jumps right away to the error captured in the catch, and this makes me show the error in the browser.

How can I make it work? Is there a way to avoid error, should I ask another question or is there a simpler way for this method?

    
asked by Juan Fernando Huenchun 16.09.2018 в 01:24
source

0 answers