首页 > 解决方案 > JSF @Inject 机制返回 NullPointerException

问题描述

在 Eclipse 上使用 JSF 和 Tomcat 时,总是返回一个空指针。这个项目是IP跟踪的,需要在应用程序bean中注入另一个bean。

待注入的Bean:跟踪使用注入的bean:increaseCount

轨道类

import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named(value = "track")
@ApplicationScoped
public class Track {
    private Map<String, Integer> map = new HashMap<>();


    public void add(String ipAddress) {
        map.put(ipAddress, map.containsKey(ipAddress) ? map.get(ipAddress) + 1 : 1);
    }

    public int getCount(String ipAddress) {
        return map.containsKey(ipAddress) ? map.get(ipAddress) : 0;
    }

    public String getAllCount() {
        return "Count summary is " + map;
    }

}

增加计数类

我尝试按照此处指示的解决方案进行操作,但遇到了同样的问题。

httpss://stackoverflow.com/questions/16399974/nullpointerexception-while-trying-to-access-inject-bean-in-constructor
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

@Named(value = "increaseCount")
@SessionScoped
public class IncreaseCount implements java.io.Serializable {
    @Inject
    private Track track;
    private String ipAddress;

    @PostConstruct
    public void init() {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        this.ipAddress = request.getRemoteAddr();
    }

    /*
     * public IncreaseCount() { HttpServletRequest request = (HttpServletRequest)
     * FacesContext.getCurrentInstance().getExternalContext() .getRequest();
     * this.ipAddress = request.getRemoteAddr(); }
     */

    public void click() {
        track.add(ipAddress);
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public int getCount() {
        return track.getCount(ipAddress);
    }
}

XHTML 页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <title>IncreaseCount</title>
</h:head>
<h:body>
    <h:form>
        <h:commandButton action="#{increaseCount.click()}" value="Click Me" />
        <br>The current count is #{increaseCount.getCount()} and your IP address is #{increaseCount.getIpAddress()}.</br>
    </h:form>
</h:body>
</html> 

例外

如您所见,调用getCount()Track 类中的方法会产生异常。

Root Cause
java.lang.NullPointerException
    chapter39.IncreaseCount.getCount(IncreaseCount.java:39)
    java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.base/java.lang.reflect.Method.invoke(Method.java:567)
    javax.el.BeanELResolver.invoke(BeanELResolver.java:158)
    javax.el.CompositeELResolver.invoke(CompositeELResolver.java:79)
    org.apache.el.parser.AstValue.getValue(AstValue.java:159)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
    com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(Unknown Source)
    com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(Unknown Source)
    com.sun.faces.facelets.compiler.TextInstruction.write(Unknown Source)
    com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(Unknown Source)
    com.sun.faces.facelets.compiler.UILeaf.encodeAll(Unknown Source)
    javax.faces.render.Renderer.encodeChildren(Unknown Source)
    javax.faces.component.UIComponentBase.encodeChildren(Unknown Source)
    javax.faces.component.UIComponent.encodeAll(Unknown Source)
    javax.faces.component.UIComponent.encodeAll(Unknown Source)
    javax.faces.component.UIComponent.encodeAll(Unknown Source)
    com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Unknown Source)
    com.sun.faces.application.view.MultiViewHandler.renderView(Unknown Source)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(Unknown Source)
    com.sun.faces.lifecycle.Phase.doPhase(Unknown Source)
    com.sun.faces.lifecycle.LifecycleImpl.render(Unknown Source)
    javax.faces.webapp.FacesServlet.service(Unknown Source)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

标签: javaeclipsetomcatjsfxhtml

解决方案


For JSF-based bean definitions:-
    javax.faces.bean.SessionScoped //for bean scoping
    javax.faces.bean.ManagedBean //for bean declaration
    javax.faces.bean.ManagedProperty //for bean injection
@ManagedProperty(value="#{yourBeanName}")
private Track track;

为了更好地理解,请通过此链接


推荐阅读