0

I'm learning Spring MVC now and trying to create simple login form. I got NullPointerException when entityManager.createQuery() method was executed. I actually tryed with defining

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

         LoginController loginController = (LoginController) context.getBean("loginController");

loginController.userService.validate(username,password);

and it works fine ,but can I use my userService without defining context and initializing loginController ?

My LoginCotroller full code :

@Controller
public class LoginController
{
    private UserService userService;

    @RequestMapping("/")
    public ModelAndView login()
 {
     ModelAndView mav =  new ModelAndView("login");
     return mav;
 }
 @RequestMapping("/validateLogin")
    public ModelAndView validateLogin(HttpServletResponse response, HttpServletRequest request)
 {
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

     LoginController loginController = (LoginController) context.getBean("loginController");

     String username = request.getParameter("username");
     String password = request.getParameter("password");

     ModelAndView mav = new ModelAndView("login");

        if(!loginController.userService.validate(username,password))
        {
            String message = "Invalid credentials";

            mav.addObject("errorMessage", message);
        }
        else
        {
            try
            {
                response.sendRedirect("/welcome");
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

     return mav;
 }

    public void setUserService(UserService userService)
    {
        this.userService = userService;
    }
}

Mu UserService code :

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

public class UserService
{
    @PersistenceContext
    private EntityManager entityManager;

    public boolean validate(String username, String password)
    {
        boolean isValid = false;

        Query query = entityManager.createQuery("from User where username = :user and password = :pass");
        query.setParameter("user",username);
        query.setParameter("pass",password);
        List result = query.getResultList();
        if(!result.isEmpty())
        {
            isValid = true;
        }
        return isValid;
    }
}

My applicationContext :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="ua.dp.advertParser"/>
    <context:annotation-config></context:annotation-config>
    <context:property-placeholder location="classpath:persistence.properties" />


    <bean id="user" class="ua.dp.advertParser.dao.entity.User" lazy-init="true"/>
    <bean id="userService" class="ua.dp.advertParser.core.UserService" lazy-init="true">
    </bean>
    <bean id="loginController" class="ua.dp.advertParser.controllers.LoginController">
        <property name="userService" ref="userService"/>
    </bean>
    <bean id="registerController" class="ua.dp.advertParser.controllers.RegisterController">
        <property name="userService" ref="userService"/>
    </bean>

    <!-- JPA & Hibernate configs -->

    <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="ua.dp.advertParser" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            </props>
        </property>
    </bean>
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.pass}" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="myEmf" />
    </bean>
    <bean id="persistenceExceptionTranslationPostProcessor"
          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

And console log :

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:986)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:800)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:497)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
    at ua.dp.advertParser.controllers.LoginController.validateLogin(LoginController.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    ... 24 more
dstiven
  • 3
  • 3
  • So the code you've posted here works? And your wondering if you have to make a loginController to get the user service? Have you tried context.getBean("userService"); ? – Mark D Apr 26 '18 at 14:49
  • @MarkD Yes , if i getting only userService it works too .Can I by configuring context or annotating avoid any bean initialization ? – dstiven Apr 26 '18 at 15:33

1 Answers1

2

You are not autowiring your userservice

Place @Autowired annotation above your User service:

@Autowired
private UserService userService;

You can autowire your setter too.

@Autwore
public void setUserService(UserService userService)
{
  this.userService = userService;
}

Also if you mark your UserService class as a @Service you do not need to put it in your xml class as long as your package to scan encompasses the package the service is in

This will make spring initialize your userService bean correctly.

http://www.baeldung.com/spring-autowire

locus2k
  • 2,802
  • 1
  • 14
  • 21