0

I have a HashMap where I am putting HttpSession object as Key and HashSet as Value

HashMap<HttpSession, HashSet<String>> map = new HashMap<HttpSession, HashSet<String>>();

I have a HttpSession listener where I need to check weather session object is exist in the Map

public void sessionDestroyed(HttpSessionEvent se) {
    HashMap<HttpSession, HashSet<String>> map = //Get map object
    HttpSession session = se.getSession();
    if(map.containsKey(session)){
        //TODO Code goes here
    }
}

IF condition always return false, even though session object is available in the map (manually checked the map entries). I am stuck!!!

user1448652
  • 169
  • 2
  • 4
  • 9
  • 1
    You should use immutatble objects as key in this case you can not guranttee equality based on `HttpSession` implementation so use `String` `id` returned by [getId()](http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#getId()) – Amit Deshpande Mar 12 '13 at 06:50
  • What value you are assgining to your map, please show that code also. Because when we open the page that time session id is differnet and after successfull login session id become somthing else. So please let me know how your hashmap is created – Ranu Jain Mar 12 '13 at 06:52
  • //Some code HttpSession session = request.getSession(true); HashSet set = new HashSet(); if(session.isNew()) map.put(session, set); //Some code – user1448652 Mar 12 '13 at 07:08
  • 1
    Please try printing the `hashcode` of the object when you put it in the map and when you retrieve it from `HttpSessionEvent`. See if they differ. – Santosh Mar 12 '13 at 07:08
  • @Santosh you are correct HashCode are different, even though the state seems to be same for both. – user1448652 Mar 12 '13 at 07:27

1 Answers1

2

If the value was put in the map in a previous request, the HttpSession object that you have now is not necessarily the same that is present in the map (even though they represent the same session). Two representations of the same session are not required (AFAIK) to be equals or to have the same hashCode, which will break the map.

You may try using the session.getId() value as key.

Javier
  • 12,100
  • 5
  • 46
  • 57