HttpSessionListener(sessionCreated / destroyed) – 奇怪的行为

我正在尝试使用HttpSessionListener:

public class SessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { System.out.println("ID Session Created: " + event.getSession().getId()); } public void sessionDestroyed(HttpSessionEvent event) { System.out.println("ID Session Destroyed: " + event.getSession().getId()); } } 

web.xml中:

  session.SessionListener  

UserManager.java

 @SessionScoped @ManagedBean(name="userManager") public class UserManager extends Tools { /**/ private static final long serialVersionUID = -8522314095497978567L; private String username; private String password; private transient HttpSession session = null; public String login() { user = (User) find(username, password); if (user != null) { username = password = null; FacesContext context = FacesContext.getCurrentInstance(); session = (HttpSession) context.getExternalContext().getSession(true); session.setAttribute("id", user.getID()); } } public void logout() { user = null; FacesContext context = FacesContext.getCurrentInstance(); session = (HttpSession) context.getExternalContext().getSession(true); session.invalidate(); } // getters and setters ---------------------------------------------------- } 

它有效,但有点奇怪。

如果我注销,它会向控制台报告:

 ID Session Destroyed: 807DEDB88D35C0351BF2B9FBA83519AB ID Session Created: 8A029C95E6BA9DF17FB91C7F3AC81B24 

如果登录,控制台中没有任何内容。

我做错了什么?

在您的浏览器向Web服务器发出请求时创建会话,而不是在您“登录”时创建。 对于服务器正在与之交互的每个客户端,将始终存在会话。 如果您在该会话中存储任何内容或以其他方式使用它并不重要。

当您注销时,强制服务器丢弃当前会话,但由于它仍然需要与客户端通信,因此会创建一个新的(“干净”)会话。 登录时,此新会话可能仍然有效。

我确定如果您关闭服务器并删除其所有工作缓存,您将在浏览器的第一次访问时看到会话创建的消息。

session = (HttpSession) context.getExternalContext().getSession(true); 注销方法中的上述行应该具有’getSession()’而不是true。

的getSession(布尔)

返回与此请求关联的当前HttpSession,如果没有当前会话且create为true,则返回新会话。