2016-03-20 108 views
0

我必須從另一個請求作用域CDI bean訪問會話範圍的CDI bean。我有:從另一個CDI bean獲取對CDI bean的訪問

  • 會話範圍的CDI Bean上保持登錄的用戶,
  • 請求範圍的CDI Bean上處理的當前登錄的用戶實例的一些數據和需求(用於此目的)。

在當我試圖讓訪問會話範圍的bean的請求範圍的bean(通過@Inject註解)當你看到下面的那一刻 - 我得到這一行的NullPointerException異常(它位於addData方法):

String surname=loginController.getCurrentUser().getSurname(); 

你能告訴我如何解決這個問題嗎?

當然,如果我從任何xhtml頁面打印例如:#{loginController.currentUser.surname},一切正常,但我需要從bean訪問,而不是從xhtml頁面訪問。

這是登錄頁面的一部分:

<h:form class="form">    

    <p:growl id="growl" showDetail="false" /> 

    <h:inputText id="username" value="#{userLogin.username}" label="Username" required="true" requiredMessage="Username: This field is required." title="Enter your username." pt:placeholder="Username" />      

    <h:inputSecret id="password" value="#{userLogin.password}" label="Password" required="true" requiredMessage="Password: This field is required." title="Enter your password." pt:placeholder="Password" />     

    <p:commandButton value="Login" action="#{loginController.login}" update="growl" styleClass="buttonStyle"/>     

</h:form> 

這是一個會話範圍CDI豆:

@Named 
@SessionScoped 
public class LoginController implements Serializable { 

    private static final long serialVersionUID = -6322113716363932422L; 

    public String login(){  

     if(userService.login(userLogin)){ 

      currentUser=userService.getCurrnetUser(userLogin.getUsername()); 

      return "home?faces-redirect=true";   
     } 
     else{ 

      facesContext.addMessage(null, new FacesMessage("Data entered are incorrect")); 
      return null; 
     } 
    } 

    public String logout(){ 

     currentUser=null; 

     return "login?faces-redirect=true"; 
    } 

    public boolean isLoggedIn() { 

      return currentUser!=null; 
    } 

    @Produces 
    @LoggedIn 
    public UserAccount getCurrentUser(){ 

     return currentUser; 
    } 

    @Inject 
    private FacesContext facesContext; 

    @Inject 
    private UserServiceImpl userService; 

    @Named 
    @Produces 
    @RequestScoped 
    private UserAccount userLogin=new UserAccount(); 

    private UserAccount currentUser; 
} 

這是一個請求範圍的CDI豆:

@Named 
@RequestScoped 
public class DataServiceImpl implements DataService { 

    @Override 
    public void addData(String[] data) { 

     //Proccess some data 

     String surname=loginController.getCurrentUser().getSurname(); 

     //Proccess some data 
    } 

    @Inject 
    private LoginController loginController; 
} 

這是一個堆棧跟蹤:

18:45:08,968 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-15) #{dataController.send()}: java.lang.NullPointerException: javax.faces.FacesException: #{dataController.send()}: java.lang.NullPointerException 
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) 
    at javax.faces.component.UICommand.broadcast(UICommand.java:315) 
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) 
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) 
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) 
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) 
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) 
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658) 
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) 
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) 
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) 
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) 
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) 
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) 
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) 
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) 
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50) 
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284) 
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263) 
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) 
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174) 
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202) 
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException 
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) 
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) 
    ... 34 more 
Caused by: java.lang.NullPointerException 
    at com.system.service.DataServiceImpl.addData(DataServiceImpl.java:24) 
    at com.system.controller.DataController.send(DataController.java:97) 
    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 javax.el.ELUtil.invokeMethod(ELUtil.java:308) 
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:415) 
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256) 
    at com.sun.el.parser.AstValue.invoke(AstValue.java:285) 
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304) 
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) 
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) 
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) 
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) 
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) 
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) 
    ... 35 more 

18:45:08,971 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-15) javax.faces.el.EvaluationException: java.lang.NullPointerException 
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) 
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) 
    at javax.faces.component.UICommand.broadcast(UICommand.java:315) 
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) 
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) 
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) 
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) 
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) 
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658) 
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) 
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) 
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) 
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) 
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) 
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) 
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) 
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) 
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50) 
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284) 
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263) 
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) 
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174) 
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202) 
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: java.lang.NullPointerException 
    at com.system.service.DataServiceImpl.addData(DataServiceImpl.java:24) 
    at com.system.controller.DataController.send(DataController.java:97) 
    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 javax.el.ELUtil.invokeMethod(ELUtil.java:308) 
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:415) 
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256) 
    at com.sun.el.parser.AstValue.invoke(AstValue.java:285) 
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304) 
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) 
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) 
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) 
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) 
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) 
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) 
    ... 35 more 

這是另一個CDI豆在位於一個send方法(從中我打電話到addData方法),我們可以在堆棧跟蹤看到:

@Named 
@ViewScoped 
public class DataController implements Serializable { 

    private static final long serialVersionUID = 1383572529241805730L; 

    //some methods 

    public void send(){ 

     if(uploadFile==null){ 

      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "The file isn't uploaded", "You should upload a file")); 
     } 
     else{ 

      //Sending the data to the database... 

      list=new ArrayList<String>(); 

      //It should be a upload file but for now I add it manually. 
      try(Stream<String> stream=Files.lines(Paths.get("F:/VirtualBox/Share/capture20110815.binetflow"))) {    

       list=stream.collect(Collectors.toList()); 

       int start=0;     
       Pattern pattern=Pattern.compile(","); 
       dataService=new DataServiceImpl(); 

       for (String s : list) { 

        if(start!=0){ 

         String[] data=pattern.split(s); 

         dataService.addData(data); 
        } 
        else start++; 
       }       

      } catch (IOException e) { 

       e.printStackTrace(); 
      }  

      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "The data has been added.", ""));   
     } 
    } 

    @Named 
    @Produces 
    @RequestScoped 
    private UserTable userTable=new UserTable(); 

    @Inject 
    private DataService dataService; 

    @Inject 
    private FacesContext facesContext; 

    @Inject 
    private Logger log; 

    private UploadedFile uploadFile; 
    private List<String> list; 
} 
+0

你確定'NullPointerException'是由'loginController'對象而不是'loginController.getCurrentUser()'造成的嗎?發佈完整的堆棧跟蹤。 – Geinmachi

+0

我很確定,因爲在我通過condidtion'if(loginController == null)'檢查了它並且我收到了'true'。我編輯了我的帖子並添加了完整的堆棧跟蹤。 – Robert

+0

異常說'#{dataController.send()}'中有'NullPointerExcpetion'。你的代碼中沒有像#{dataController.send()}這樣的東西。 – Geinmachi

回答

0

我找到了解決辦法。一步一步我所做的:

  1. 我從DataServiceImpl豆刪除LoginController和我一起@LoggedIn註釋注入UserAccountDataController豆:

    @Named 
    @ViewScoped 
    public class DataController implements Serializable { 
    
        //other fields and methods 
    
        @Inject 
        @LoggedIn 
        private UserAccount currentUser; 
    } 
    

    您也可以注入LoginControllerDataController bean代替UserAccount,但不推薦。你會更好,如果你注入UserAccount

  2. 我在DataServiceImpl類中創建了addCurrnetUser()方法。該方法的參數是UserAccount對象:

    @Named 
    @RequestScoped 
    public class DataServiceImpl implements DataService { 
    
        @Override 
        public void addCurrentUser(UserAccount currentUser){ 
    
         this.currentUser=currentUser; 
        } 
    
        @Override 
        public void addData(String[] data) { 
    
         //Proccess some data 
    
         String surname=loginController.getCurrentUser().getSurname(); 
    
         //Proccess some data 
        } 
    
        private UserAccount currentUser; 
    } 
    
  3. 我稱爲在send()方法(其位於DataController豆)dataService.addCurrentUser(currentUser)調用dataService.addData()之前。

你也可以有一個問題:爲什麼在DataServiceImpl豆,並在DataController豆未注入LoginController回報null?看看this的討論。你可以在這裏找到一些原因。