为什么在JAVA中session.invalidate()之后会话不为空?

Vis*_*kia 9 java session invalidation

在开发JavaEE WEB应用程序时,我面临着非常奇怪的问题.

即使在HttpSession使用失效后session.invalidate();,我也没有得到会话null.有一种情况,我在执行无效会话后有一个如下执行的语句.

if (null != session && null != session.getAttribute("loginToken")){
   //do something
}
Run Code Online (Sandbox Code Playgroud)

我没有在这里获得会话null,所以第二个条件将尝试执行.因此会话不是空的,所以我得到IllegalStateException- session is already invalidated.但是为什么会话在使它失效后不为空?:(

Adr*_*ter 13

调用session.invalidate()从注册表中删除会话.getSession(false)之后调用 将返回null(请注意,getSession()或者getSession(true)在这种情况下将创建一个新会话).调用invalidate()还将删除绑定到会话的所有会话属性.但是,如果您的代码仍然具有对会话或其任何属性的引用,那么这些仍然可以访问:

    // create session if none exists (default) and obtain reference
    HttpSession session = request.getSession();

    // add a session attribute
    session.setAttribute("lollypop", "it's my party");

    // obtain reference to session attribute 
    Object lollypop = session.getAttribute("lollypop");

    // print session ID and attribute
    System.out.println(session.getId());
    System.out.println(lollypop);

    session.invalidate();

    // session invalidated but reference to it still exists
    if (session == null) {            
        System.out.println("This will never happen!");
    }

    // print ID from invalidated session and previously obtained attribute (will be same as before)
    System.out.println(session.getId());
    System.out.println(lollypop);

    // print 'null' (create=false makes sure no new session is created)
    System.out.println(request.getSession(false));
Run Code Online (Sandbox Code Playgroud)

示例输出:

1k47acjdelzeinpcbtczf2o9t
it's my party
1k47acjdelzeinpcbtczf2o9t
it's my party
null
Run Code Online (Sandbox Code Playgroud)

到目前为止的解释.要解决您的问题,您应该:

HttpSession existingSession = request.getSession(false);
if (existingSession != null && existingSession.getAttribute("loginToken") != null){
   //do something
}
Run Code Online (Sandbox Code Playgroud)


小智 1

尝试将 false 作为参数传递给 getSession(boolean) 。如果存在的话,这将返回一个会话,否则将返回 null。

HttpSession session = request.getSession(false);
if(session==null || !request.isRequestedSessionIdValid() )
{
    //comes here when session is invalid.

}
Run Code Online (Sandbox Code Playgroud)