我在开发 JavaEE WEB 应用程序时遇到了一个非常奇怪的问题。
即使在使用 session.invalidate();
使 HttpSession
无效之后,我也没有得到 session null
。有一种情况,在使 session 无效后,我有一个语句正在执行,如下所示。
if (null != session && null != session.getAttribute("loginToken")){
//do something
}
我在这里没有得到空 session ,所以第二个条件将尝试执行。因此 session 不为空,所以我得到 IllegalStateException
- session is already invalidated
。但是为什么session在失效后不为null?? :(
最佳答案
调用 session.invalidate()
从注册表中删除 session 。之后调用 getSession(false)
将返回 null(请注意,在这种情况下,getSession()
或 getSession(true)
将创建一个新 session ,见 HttpServletRequest API )。调用 invalidate()
还将删除绑定(bind)到 session 的所有 session 属性。但是,如果您的代码仍然引用 session 或其任何属性,那么它们仍然可以访问:
// 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));
示例输出:
1k47acjdelzeinpcbtczf2o9t
it's my party
1k47acjdelzeinpcbtczf2o9t
it's my party
null
到目前为止的解释。要解决您的问题,您应该这样做:
HttpSession existingSession = request.getSession(false);
if (existingSession != null && existingSession.getAttribute("loginToken") != null){
//do something
}
关于java - 为什么在 JAVA 中 session.invalidate() 之后 session 不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24677949/