HttpSessionListener(sessionCreated/destroyed)-奇怪的行为 [英] HttpSessionListener (sessionCreated/destroyed) - strange behaviour

查看:201
本文介绍了HttpSessionListener(sessionCreated/destroyed)-奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HttpSessionListener:

I'm trying to use 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:

<listener>
  <listener-class>session.SessionListener</listener-class>
</listener>

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 ----------------------------------------------------
}

它有效,但有点奇怪.

It works, but little bit strangely.

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

If i logout, it reports to the console:

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

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

If login, there is nothing in console.

我做错了什么?

推荐答案

会话是在您的浏览器向Web服务器发出请求时创建的,而不是在您登录"时创建的.服务器与之交互的每个客户端始终存在一个会话.无论您在该会话中存储任何内容还是以其他方式使用它,都没有关系.

A session is created the moment your browser makes a request to the webserver, not when you 'log in'. A session will always exist for each client that the server is interacting with. It does not matter if you store anything in that session or otherwise make use of it.

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

When you logout, you force the server to discard the current session, but since it still needs to communicate with the client a new ('clean') session is created. This new session is likely still in effect when you log in.

我确定,如果您关闭服务器并删除其所有工作缓存,则在浏览器的第一次点击中您会看到会话创建消息.

I'm sure if you shut down your server and delete all its working cache, you'll see the session created message on the first hit from your browser.

这篇关于HttpSessionListener(sessionCreated/destroyed)-奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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