Search code examples
springhibernatespring-mvcservicecontrollers

I have NullException on login


I'm trying to make a login, first time on mvc

I have this error on a proyect for university and I'm not able to see the error throw debug, I can't figure out why. When the debugger gets to line :

Empleado empleado = serviceEmpleado.correctLogin(loginFormDni, loginForm.getPassword());

on controller LoginController method checkLogin it just gives me the exception.

type Informe de Excepción

mensaje Request processing failed; nested exception is java.lang.NullPointerException

descripción El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.

excepción

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
causa raíz

java.lang.NullPointerException
    germanAcosta.electronicaDonPepe.controller.LoginController.checkLogin(LoginController.java:36)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
nota La traza completa de la causa de este error se encuentra en los archivos de diario de Apache Tomcat/8.0.36.

class LoginController

package germanAcosta.electronicaDonPepe.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import germanAcosta.electronicaDonPepe.DTO.Login;
import germanAcosta.electronicaDonPepe.dominio.Empleado;
import germanAcosta.electronicaDonPepe.service.ServicioException;

@Controller
//@SessionAttributes("resultado")
public class LoginController {

    public ServiceEmpleado serviceEmpleado;

    @RequestMapping("/login")
    public String showLogin(Model model,
            @ModelAttribute("resultado") String resultado, @ModelAttribute("error") String error) {
        Login login = new Login();
        model.addAttribute("login", login);
        model.addAttribute("resultado", resultado);
        model.addAttribute("error", error);

        return "login";
    }


    @RequestMapping(value = "/login/check", method = RequestMethod.POST)
    public String checkLogin(@ModelAttribute("login") Login loginForm, Model model, RedirectAttributes ra) {

        try {
            Integer loginFormDni = loginForm.getDni();

            Empleado empleado = serviceEmpleado.correctLogin(loginFormDni, loginForm.getPassword());

            model.addAttribute("loginForm", loginForm);

            ra.addFlashAttribute("resultado", "El login es correcto bienvenido " + empleado.getNombre() + ".");  

            return "redirect:/login";

        } catch (ServicioException e) {
            ra.addFlashAttribute("resultado", e.getMessage());
            return "redirect:/login";
        } catch (Exception e) {
            ra.addFlashAttribute("error", e.getCause()+ "error");
            ra.addFlashAttribute("resultado", "El resultado no es el esperado");
            return "redirect:/login";
        }
    }
}

Class ServiceEmpleado

package germanAcosta.electronicaDonPepe.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import germanAcosta.electronicaDonPepe.dominio.Empleado;
import germanAcosta.electronicaDonPepe.repository.IEmpleadoDAO;
import germanAcosta.electronicaDonPepe.service.ServicioException;

@Service
public class ServiceEmpleado {

@Autowired
private IEmpleadoDAO empleadoDAO;

public Empleado correctLogin(Integer dni, String password) throws ServicioException {

    Empleado empleado = this.empleadoDAO.getById(dni);

    if (empleado == null) {

        throw new ServicioException("El usuario no existe");

    } else if (empleado.getPassword() != password) {

        throw new ServicioException("El password es incorrecto, por favor reintente nuevamente");

    } else {

        return empleado;

    }

}
}

Login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Electronica Don Pepe</title>
</head>
<body>
    <h1>login.jsp</h1>

    <br>
    <sf:form action="${pageContext.request.contextPath}/login/check"
        method="post" commandName="login">
        <table>
            <tr>
                <td><sf:label path="dni">Ingrese su dni</sf:label></td>
                <td><sf:input path="dni" type="text" /></td>
            </tr>
            <tr>
                <td><sf:label path="password">Ingrese su contraseña</sf:label></td>
                <td><sf:input path="password" type="text" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Ingresar"></td>
            </tr>
        </table>
    </sf:form>
    <c:out value="${resultado}"></c:out>
    <c:out value="${loginForm.password}"></c:out>
</body>
</html>

Thanks in advance


Solution

  • I use @Autowired on my ServiceEmpleado as @Yuva suggested, but I realized that the annotation it's for an interface and not for a class. So I changed the ServiceEmpleado name to ServiceEmpleadoImpl and add an interface implementation to that class called IServiceEmpleado.

    Then I add @Transactional to ServiceEmpleadoImpl and configured the bean on my Config.java

    That resolved the problem. Thanks