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

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

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

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

我没有在这里获得会话null因此第二个条件将尝试执行。 因此session不为null,因此我收到IllegalStateExceptionsession is already invalidated 。 但是为什么会话在使其失效后不为空? 🙁

调用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 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 

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

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

invalidate方法执行以下操作(来自API ):

Invalidates this session then unbinds any objects bound to it.

它没有说明HttpSession -object本身,但会使会话的变量无效。 如果调用类的方法,则在该方法调用之后该对象不可能为null 。 如果您的会话之后应该为null,则该方法必须包含类似于以下内容的行: this = null; 这是不可能的。 为无效会话抛出exception是首选方法。

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

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