为什么在JAVA中session.invalidate()之后会话不为空? [英] Why session is not null after session.invalidate() in JAVA?

查看:1357
本文介绍了为什么在JAVA中session.invalidate()之后会话不为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发JavaEE WEB应用程序时遇到了一个非常奇怪的问题。

I am facing very strange problem while developing JavaEE WEB Application.

即使在使用<无效 HttpSession 之后code> session.invalidate(); ,我没有得到会话 null 。有一种情况,我在会话无效后会执行一条如下所示的声明。

Even after invalidating the HttpSession using session.invalidate();, I am not getting session null. There is a case where I have one statement in execution like below after invalidating session.

if (null != session && null != session.getAttribute("loginToken")){
   //do something
}

我在这里没有得到会话空,所以第二个条件会尝试执行。因此会话不为空,所以我得到 IllegalStateException - 会话已经失效。但是为什么会话在使其失效后不为空? :(

I am not getting session null here so second condition will try to execute. And hence session is not null, so I am getting IllegalStateException - session is already invalidated. But why session is not null after invalidating it?? :(

推荐答案

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

Calling session.invalidate() removes the session from the registry. Calling getSession(false) afterwards will return null (note that getSession() or getSession(true) will create a new session in this case). Calling invalidate() will also remove all session attributes bound to the session. However if your code still has references to the session or any of its attributes then these will still be accessible:

    // 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 and attribute from invalidated session (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));

示例输出:

1k47acjdelzeinpcbtczf2o9t
it's my party
1k47acjdelzeinpcbtczf2o9t
it's my party
null

目前为止的解释。要解决您的问题,您应该这样做:

So far for the explanation. To solve your problem you should do:

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

这篇关于为什么在JAVA中session.invalidate()之后会话不为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆