spring和MessagesSource空指针异常

时间:2013-09-06 21:34:31

标签: java spring hibernate spring-mvc

任何人都可以告诉我为什么我会在null pointer exception的结果课中获得这个messageSource吗?

我跟着这个。 http://www.mkyong.com/spring/spring-how-to-access-messagesource-in-bean-messagesourceaware/

并且可以在我的控制器中使用消息源,如下所示:

工作代码:---

  package web.controller;

  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpSession;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.MessageSource;
  import org.springframework.security.core.Authentication;
  import org.springframework.security.core.context.SecurityContextHolder;
  import org.springframework.security.core.userdetails.User;
  import org.springframework.stereotype.Controller;
  import org.springframework.ui.ModelMap;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RequestParam;
  import web.entity.Users;
  import web.service.UserService;
  import web.service.common.Result;
  //import javax.servlet.http.HttpServletRequest;
  //import javax.servlet.http.HttpSession;

  /**
  *
  * @author syncsys
  */

  @Controller
  public class UserController {
      @Autowired
      private UserService userService;
      @Autowired
      private MessageSource messages;


      @RequestMapping(value = "/login", method = RequestMethod.GET)
      public String getLoginPage(@RequestParam(value="error", required=false) boolean error,
    ModelMap model) {
      System.out.println("Received request to show login page");


      String message =  null;
      if (error == true) {
      message = messages.getMessage("message.invalidCreds",  new Object [] {"UserName"}, "Invalid credentials", null);
    // Assign an error message
    model.put("invalidCreds", message);
      } else {
    model.put("invalidCreds", "");
      }

      return "/login/login";
      }

主要错误:

      web.service.common.Result.<init>(Result.java:29)
          web.service.UserServiceImpl.save(UserServiceImpl.java:30)

          web.controller.UserController.createAdmin(UserController.java:121)

调试:

      debug --- a
      debug --- b
      Hibernate: select users0_.id as id1_15_, users0_.description as descript2_15_, users0_.email as email3_15_, users0_.isEnabled as isEnable4_15_, users0_.name as name5_15_, users0_.password as password6_15_, users0_.type as type7_15_ from Users users0_ where users0_.email=?
      debug --- d
      result class test ---------  1

道:

      public Users save(Users user) {

              Users userToBeReturned = entityManager.merge(user);
              return userToBeReturned;
          }

          public boolean doesLoginIdExists(String email){
              System.out.println("debug --- a");
              String queryString = "SELECT user FROM Users AS user " +
                  "WHERE user.email = :email";
              Query query = entityManager.createQuery(queryString);
              query.setParameter("email", email);
              System.out.println("debug --- b");
              List<?> list = query.getResultList();
              if(list == null || list.size() == 0){
              System.out.println("debug --- c");
              return false;
              }else{
              System.out.println("debug --- d");
              return true;
              }


          }

服务:

      public Result save(Users user){
          if( userDAO.doesLoginIdExists(user.getEmail()) ){

      ############## line 30 #############################################
          return new Result(false,null,Arrays.asList("error.emailAlreadyExists"/*,"string"*/) );
          }else{

          Users userToBeReturned = userDAO.save(user);

          return new Result(true,userToBeReturned,Arrays.asList("success.userCreated"/*,"string"*/));
          }

控制器:

      @RequestMapping("/users/createadmin")
      public String createAdmin(ModelMap model){
          Users user = new Users();
          user.setEmail("admin@admin.com");
          user.setName("Admin");
          user.setPassword("admin");
      ############## line 121 ##################################################
          Result result = userService.save(user);
          if(result.getIsSuccessful()){
          model.put("successMessages", result.getMessageList());
          }else{
          model.put("errorMessages", result.getMessageList());
          }
          return "/users/createadmin";       
      }

结果类

      /*
      * To change this template, choose Tools | Templates
      * and open the template in the editor.
      */
      package web.service.common;

      import java.util.ArrayList;
      import java.util.List;
      import java.util.Locale;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.MessageSource;
      import org.springframework.context.MessageSourceAware;
      import org.springframework.context.MessageSourceResolvable;
      import org.springframework.context.NoSuchMessageException;

      /**
      *
      * @author syncsys
      */
      public class Result implements MessageSourceAware{
      private boolean isSuccessful;
      private Object object;
      private List messageList = new ArrayList();
      @Autowired
      private MessageSource messageSource;


      public Result(boolean isSuccessful, Object object, List errorList){
          this.isSuccessful = isSuccessful;
          this.object = object;
          if(errorList != null){
          for (Object error : errorList){
      System.out.println("result class test ---------  1");
      #########################line 29 ###################
              String errorMessage = messageSource.getMessage((String)error,  new Object [] {"error-"}, "error-", null);
      System.out.println("result class test ---------  2");                 
              this.messageList.add(errorMessage);
      System.out.println("result class test ---------  3");

          }
          }
      }

      /**
      * @return the isSuccessful
      */
      public boolean getIsSuccessful() {
          return isSuccessful;
      }

      /**
      * @param isSuccessful the isSuccessful to set
      */
      public void setIsSuccessful(boolean isSuccessful) {
          this.isSuccessful = isSuccessful;
      }

      /**
      * @return the object
      */
      public Object getObject() {
          return object;
      }

      /**
      * @param object the object to set
      */
      public void setObject(Object object) {
          this.object = object;
      }

      /**
      * @return the messageList
      */
      public List getMessageList() {
          return messageList;
      }

      /**
      * @param messageList the messageList to set
      */
      public void setMessageList(List messageList) {
          this.messageList = messageList;
      }

      @Override
      public void setMessageSource(MessageSource messageSource) {
          this.messageSource = messageSource;
      }

      }

详细错误:

      HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException

      type Exception report

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

      description The server encountered an internal error that prevented it from fulfilling this request.

      exception

      org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
          org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
          org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
          javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
          org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
          javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
          org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
          org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
          org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
          org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
          org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
      root cause

      java.lang.NullPointerException
          web.service.common.Result.<init>(Result.java:29)
          web.service.UserServiceImpl.save(UserServiceImpl.java:30)
          sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          java.lang.reflect.Method.invoke(Method.java:601)
          org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
          org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
          org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
          org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
          org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
          org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
          org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
          org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
          $Proxy50.save(Unknown Source)
          web.controller.UserController.createAdmin(UserController.java:121)
          sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          java.lang.reflect.Method.invoke(Method.java:601)
          org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
          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:745)
          org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
          org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
          org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
          org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
          org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
          org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
          javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
          org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
          javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
          org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
          org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
          org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
          org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
          org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
          org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
      note The full stack trace of the root cause is available in the Apache Tomcat/7.0.32 logs.

      Apache Tomcat/7.0.32

1 个答案:

答案 0 :(得分:1)

在服务类的save方法中,您要实例化Result类。

new Result(false,null,Arrays.asList("error.emailAlreadyExists"/*,"string"*/) );

Result课程中,您Autowiring字段MessageSource

@Autowired
private MessageSource messageSource;

spring无法自动装配您实例化的任何字段。

对于Spring Autowire任何字段,您需要允许spring实例化(维护)Result对象。