尝试在Spring MVC控制器

时间:2018-04-26 14:34:36

标签: java spring spring-mvc

我现在正在学习Spring MVC并尝试创建简单的登录表单。 执行entityManager.createQuery()方法时,我得到了NullPointerException。 我实际上尝试了定义

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

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

loginController.userService.validate(username,password);

它工作正常,但我可以使用我的userService而无需定义上下文并初始化loginController吗?

我的LoginCotroller完整代码:

@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代码:

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;
    }
}

我的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" />

和控制台日志:

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

1 个答案:

答案 0 :(得分:2)

您没有自动装配用户服务

@Autowired注释放在用户服务上方:

@Autowired
private UserService userService;

您也可以自动装配您的二传手。

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

此外,如果您将UserService类标记为@Service,只要您要扫描的包包含服务所在的包

,您就不需要将它放在xml类中。

这将使spring正确初始化你的userService bean。

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