【问题标题】:HttpSession is nullHttpSession 为空
【发布时间】:2012-10-27 11:05:13
【问题描述】:
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 没有。

【问题讨论】:

    标签: jsf servlets


    【解决方案1】:

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

    正如其javadoc 所指出的那样,当您尝试访问一个变量或使用句点. 操作符调用一个方法时,NullPointerException 将被抛出,而对象引用实际上是 null.

    例如

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

    在您的特定情况下,您试图在 null 对象上调用方法 isNew()。因此这是不可能的。 null 引用根本没有方法。它只是指向nothing。您应该改为进行空检查。

    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.
    }
    

    当会话尚未创建时,带有false 参数的getSession() 调用可能即返回null。另见javadoc

    getSession

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

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

    看强调的部分。

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

    getSession

    HttpSession getSession()
    

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

    看强调的部分。

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

    【讨论】:

      【解决方案2】:

      getSession() 的默认设置是在没有当前会话的情况下创建一个新的会话。

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

      【讨论】:

        猜你喜欢
        • 2012-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-27
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多