Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpSessionListener (sessionCreated/destroyed) - strange behaviour

Tags:

java

servlets

jsf

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.

What I'm doing wrong?

like image 449
gaffcz Avatar asked May 30 '11 11:05

gaffcz


2 Answers

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.

like image 174
Kris Avatar answered Oct 16 '22 09:10

Kris


session = (HttpSession) context.getExternalContext().getSession(true); The above line in the logout method should have 'getSession()' without true.

getSession(boolean)

Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.

like image 22
sudmong Avatar answered Oct 16 '22 08:10

sudmong