1
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

为什么案例 A 抛出 NullPointerException 而案例 B 不是。

4

2 回答 2

6

首先,了解何时以及为什么NullPointerException抛出a很重要。你提出问题的方式表明你不明白。你问“为什么它会抛出NullPointerException?”。您没有问“为什么它会返回null?”。

正如其javadoc所指出的,NullPointerException当您尝试访问变量或使用句.点运算符调用实际上是 null.

例如

SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!

在您的特定情况下,您试图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.
}

getSession()带有false参数的调用可能会null在会话尚未创建时返回。另请参阅javadoc

获取会话

public abstract java.lang.Object getSession(boolean create)

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

见强调部分。

HttpServletRequest#getSession()不带任何参数的调用,默认使用true作为create参数。另请参阅javadoc

获取会话

HttpSession getSession()

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

见强调部分。

我希望您将此作为提示,以便更好地查阅 javadocs。它们通常已经包含了您问题的答案,因为它们非常准确地描述了类和方法的作用。

于 2012-10-27T11:29:25.077 回答
1

如果没有当前会话,getSession() 的默认设置是创建一个新会话。

如果没有活动会话,使用 getSession(false) 会更改此行为以返回 null。

于 2012-10-27T11:07:53.393 回答