注入bean将返回null

时间:2016-03-10 19:08:11

标签: jsf cdi inject

我有两个网页,每个网页都有一个bean支持,以及在Glassfish 4.0服务器上运行的多个DAO。第一页是登录页面 - 一切正常,我可以访问注入的对象。

然而,在第二页上,每当我尝试访问其中一个注入的对象时,我都会得到一个nullpointer-exception。

这是我的(工作)登录页面:

@ViewScoped
@Named
public class indexController implements Serializable {

private static final Logger log = Logger.getLogger(indexController.class.getName());

private String passwort, growlMsg;
@Inject
Manager manager;
@Inject
PersonalDAO personalDAO;

public indexController() {
}

public String login() {
    System.out.println("------------------LOGIN-----------------------\n"
            + "Werk: " + getWerk() + "\n"
            + "Mandant: " + getMandant() + "\n"
            + "Personalnr:" + getPersnr() + "\n"
            + "Passwort: " + passwort + "\n"
            + "----------------------------------------------");
    if (isValidUser()) {
        manager.setUserVerified(true);
        return "main";
    } else {
        FacesContext ctx = FacesContext.getCurrentInstance();
        ctx.addMessage(null, new FacesMessage("Login failed.", "Please verify your login credentials."));
        return "index";
    }
}

//TODO: Implement hashing and salting
private boolean isValidUser() {
    List<Personal> pers = personalDAO.find(getPersnr());
    if (pers.isEmpty()) {
        return false;
    }
    Personal personal = pers.get(0);
    if (personal.getWerk().getId() != getWerk()) {
        return false;
    }
    if (personal.getMandant().getId() != getMandant()) {
        return false;
    }
    if (!personal.getPasswort().equals(passwort)) {
        return false;
    }
    return true;
}

private boolean isInteger(String n) {
    try {
        Integer.parseInt(n);
    } catch (NumberFormatException ex) {
        return false;
    }
    return true;
}

public int getMandant() {
    return manager.getMandant();
}

public void setMandant(int mandant) {
    manager.setMandant(mandant);
}

public int getWerk() {
    return manager.getWerk();
}

public void setWerk(int werk) {
    manager.setWerk(werk);
}

public int getPersnr() {
    return manager.getPersnr();
}

public void setPersnr(int persnr) {
    manager.setPersnr(persnr);
}

public String getPasswort() {
    return passwort;
}

public void setPasswort(String passwort) {
    this.passwort = passwort;
}

public String getGrowlMsg() {
    return growlMsg;
}

public void setGrowlMsg(String growlMsg) {
    this.growlMsg = growlMsg;
}

}

这是我遇到问题的bean:

@RequestScoped
@Named
public class mainController implements Serializable { 
private List<Abwesenheit> abwesenheit;
private List<Personal> personal;
@Inject
Manager manager;
@Inject
PersonalDAO personalDAO;
@Inject
AbwesenheitDAO abwesenheitDAO;

public mainController() {
    System.out.println("-----MAINCONTROLLER CALLED-----");
    System.out.println(manager.isUserVerified());
    System.out.println("-----------------------------------");
}

public List<Abwesenheit> getAbwesenheit() {
    return abwesenheit;
}

public void setAbwesenheit(List<Abwesenheit> abwesenheit) {
    this.abwesenheit = abwesenheit;
}

public List<Personal> getPersonal() {
    return personal;
}

public String getVerified() {
    return manager.isUserVerified()?"Verified":"Not Verified";
}

}

经理班:

@SessionScoped
public class Manager implements Serializable {
    //TODO: Use an enum for access-levels instead of just access/no access
    private boolean userVerified = false;
    int werk, mandant, persnr;

    public Manager() {
    }

    public boolean isUserVerified() {
        return userVerified;
    }

    public void setUserVerified(boolean userVerified) {
        this.userVerified = userVerified;
    }

    public int getWerk() {
        return werk;
    }

    public void setWerk(int werk) {
        this.werk = werk;
    }

    public int getMandant() {
        return mandant;
    }

    public void setMandant(int mandant) {
        this.mandant = mandant;
    }

    public int getPersnr() {
        return persnr;
    }

    public void setPersnr(int persnr) {
        this.persnr = persnr;
    }





}

personalDAO class:

@Stateless
public class PersonalDAO implements Serializable {
    @PersistenceContext(unitName="GFOS_AwardPU")
    private EntityManager entityManager;

    public List<Personal> getPersonal() {
        return entityManager.createNamedQuery("Personal.findAll", Personal.class).getResultList();
    }

    public List<Personal> find(String personalNr) {
        Query query = entityManager.createNamedQuery("Personal.findByPersonalnr");
        query.setParameter("personalnr", personalNr);
        return query.getResultList();
    }
    public List<Personal> find(int personalNr) {
        Query query = entityManager.createNamedQuery("Personal.findByPersonalnr");
        query.setParameter("personalnr", personalNr);
        return query.getResultList();
    }

    public List<Personal> find(String personalNr, String name, String vorname, String mandant, String werk) {

        String query = "SELECT * FROM Personal WHERE 1=1";
        if(personalNr != null && !personalNr.isEmpty()) {
            query += " AND Personalnr="+personalNr;
        }
        if(name != null && !name.isEmpty()) {
            query += " AND name='"+name+"'";
        }
        if(vorname != null && !vorname.isEmpty()) {
            query += " AND vorname='"+vorname+"'";
        }
        if(mandant != null && !mandant.isEmpty()) {
            query += " AND mandant="+mandant;
        }
        if(werk != null && !werk.isEmpty()) {
            query += " AND werk="+werk;
        }
        return entityManager.createNativeQuery(query, Personal.class).getResultList();
    }
}

这是Glassfish服务器日志提取,之前没有例外:

[2016-03-10T19:43:21.303+0100] [glassfish 4.0] [INFO] [] [] [tid: _ThreadID=22 _ThreadName=Thread-3] [timeMillis: 1457635401303] [levelValue: 800] [[
  -----MAINCONTROLLER CALLED-----]]

[2016-03-10T19:43:21.304+0100] [glassfish 4.0] [SEVERE] [] [javax.enterprise.resource.webcontainer.jsf.application] [tid: _ThreadID=22 _ThreadName=http-listener-1(5)] [timeMillis: 1457635401304] [levelValue: 1000] [[
  Error Rendering View[/main.xhtml]
java.lang.NullPointerException
    at controller.mainController.<init>(mainController.java:38)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:79)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:63)
    at org.jboss.weld.injection.producer.AbstractInstantiator.newInstance(AbstractInstantiator.java:29)
    at org.jboss.weld.injection.producer.DefaultInstantiator.newInstance(DefaultInstantiator.java:90)
    at org.jboss.weld.injection.producer.BasicInjectionTarget.produce(BasicInjectionTarget.java:86)
    at org.jboss.weld.injection.producer.BeanInjectionTarget.produce(BeanInjectionTarget.java:172)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:157)
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:716)
    at org.jboss.weld.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:133)
    at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:96)
    at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
    at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
    at com.sun.faces.renderkit.html_basic.LabelRenderer.encodeBegin(LabelRenderer.java:120)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:869)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1854)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Unknown Source)
]]

[2016-03-10T19:43:21.358+0100] [glassfish 4.0] [INFO] [] [] [tid: _ThreadID=22 _ThreadName=Thread-3] [timeMillis: 1457635401358] [levelValue: 800] [[
  -----MAINCONTROLLER CALLED-----]]

[2016-03-10T19:43:21.375+0100] [glassfish 4.0] [FATAL] [jsf.context.exception.handler.log] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=22 _ThreadName=http-listener-1(5)] [timeMillis: 1457635401375] [levelValue: 1100] [[
  JSF1073: java.lang.NullPointerException erfasst w?hrend Verarbeitung von RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=null]]

[2016-03-10T19:43:21.376+0100] [glassfish 4.0] [FATAL] [] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=22 _ThreadName=http-listener-1(5)] [timeMillis: 1457635401376] [levelValue: 1100] [[

java.lang.NullPointerException
    at controller.mainController.<init>(mainController.java:38)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:79)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:63)
    at org.jboss.weld.injection.producer.AbstractInstantiator.newInstance(AbstractInstantiator.java:29)
    at org.jboss.weld.injection.producer.DefaultInstantiator.newInstance(DefaultInstantiator.java:90)
    at org.jboss.weld.injection.producer.BasicInjectionTarget.produce(BasicInjectionTarget.java:86)
    at org.jboss.weld.injection.producer.BeanInjectionTarget.produce(BeanInjectionTarget.java:172)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:157)
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:716)
    at org.jboss.weld.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:133)
    at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:96)
    at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
    at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
    at com.sun.faces.renderkit.html_basic.LabelRenderer.encodeBegin(LabelRenderer.java:120)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:869)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1854)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Unknown Source)
]]

为什么它不能在mainController类中运行?我试过改变这两个课程的范围,但这没有帮助。 Netbeans没有显示任何错误。我也试过通过Netbeans或手动启动Glassfish。我尝试的最后一件事是改变

的导入
import javax.faces.bean.RequestScoped

(以及经理类的SessionScoped)

import javax.enterprise.context.RequestScoped

但它没有解决我的问题。

1 个答案:

答案 0 :(得分:3)

而不是构造函数

public mainController() {
    System.out.println("-----MAINCONTROLLER CALLED-----");
    System.out.println(manager.isUserVerified());
    System.out.println("-----------------------------------");
}

使用带注释@PostConstruct的方法。

@PostConstruct
private void init() {
    System.out.println("-----MAINCONTROLLER INITIALIZED-----");
    System.out.println(manager.isUserVerified());
    System.out.println("-----------------------------------");
}

依赖关系尚未在构造函数中注入,可以在创建对象后访问它们。