HttpSession为空

Vha*_*ant 1 jsf servlets

A)         FacesContext facesContext = FacesContext.getCurrentInstance();
           ExternalContext externalContext=facesContext.getExternalContext();
           HttpSession session = (HttpSession) externalContext.getSession(false);

               if(session.isNew()) {            //  java.lang.NullPointerException

B)         HttpServletRequest req1 = (HttpServletRequest)FacesContext.getCurrentInstance()
                                    .getExternalContext().getRequest();
           HttpSession session1=req1.getSession();

             if(session1.isNew()) {            // no Exception
Run Code Online (Sandbox Code Playgroud)

为什么案例A抛出NullPointerException,而案例B则没有.

Bal*_*usC 6

首先,要了解是很重要的,当为什么一个NullPointerException是被扔.你提出问题的方式表明你不理解它.你问"它为什么扔NullPointerException?".你没有问"它为什么会回来null?".

正如其javadoc所示,NullPointerException当您尝试访问变量或在实际.的对象引用上使用period 运算符调用方法时,将抛出该异常. null

例如

SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!
Run Code Online (Sandbox Code Playgroud)

在您的特定情况下,您尝试isNew()null对象上调用该方法.因此这是不可能的.该null引用根本没有方法.它只是毫无意义.你应该做一个空检查.

HttpSession session = (HttpSession) externalContext.getSession(false);

if (session == null) {
    // There's no session been created during current nor previous requests.
}
else if (session.isNew()) {
    // The session has been created during the current request.
}
else {
    // The session has been created during one of the previous requests.
}
Run Code Online (Sandbox Code Playgroud)

getSession()false参数的调用可能null在尚未创建会话时返回.另见javadoc:

的getSession

public abstract java.lang.Object getSession(boolean create)
Run Code Online (Sandbox Code Playgroud)

如果create参数是true,则创建(如果需要)并返回与当前请求关联的会话实例.如果create参数false返回与当前请求关联的任何现有会话实例,或者null如果没有此类会话则返回.

见重点部分.

HttpServletRequest#getSession()不带任何参数的调用默认使用true作为create参数.另见javadoc:

的getSession

HttpSession getSession()
Run Code Online (Sandbox Code Playgroud)

返回与此请求关联的当前会话,或者如果请求没有会话,则创建一个会话.

见重点部分.

我希望你能把它作为暗示更好地参考javadocs.它们通常已经包含了您的问题的答案,因为它们非常精确地描述了类和方法的作用.