tags:

views:

36

answers:

2

I am using the following code to remove a attribute from session

List<User> l=(List<User>) sess.getAttribute("allUserslist");
for(int ii=0;ii<l.size();ii++){
    System.out.println("bef"+l.get(ii).getLoginName()+optionSelected[i]);
    if(l.get(ii).getLoginName().equals(optionSelected[i])){
        System.out.println("in iteration");
        sess.removeAttribute(l.get(ii).getLoginName());
        List<User> l1=(List<User>) sess.getAttribute("allUserslist");
        System.out.println("final size"+l1.size());
    }
}

The final size after removing is still one as before, where am I going wrong?

A: 

Let's think what exactly you trying to do.

  1. You store the list with users credentials in session object.
  2. You retrieve the list and want to delete user from the list.
  3. You want to see deletion update in the session as well.

But by doing:

sess.removeAttribute(l.get(ii).getLoginName());

You actually do not delete anything, since there is no such element stored in the session previously.

So you need to get the list from the session, remove user from this list.

List<User> l=(List<User>) sess.getAttribute("allUserslist");
for(int ii=0;ii<l.size();ii++){
    System.out.println("bef"+l.get(ii).getLoginName()+optionSelected[i]);
    if(l.get(ii).getLoginName().equals(optionSelected[i])){
        System.out.println("in iteration");
        l.remove(ii)); // Remove user from the list
    }
}

List<User> l1=(List<User>) sess.getAttribute("allUserslist");
System.out.println("final size"+l1.size());
Artem Barger
Each time a user is removed from the list, the next one is skipped, and setting the "allUsersList" attribute at each iteration is pointless.
Maurice Perry
A: 

Your code is removing the attribute named after the user, but it does not remove the user from the list. To do so:

List<User> l=(List<User>) sess.getAttribute("allUserslist");
for(int ii=0;ii<l.size();){
    System.out.println("bef"+l.get(ii).getLoginName()+optionSelected[i]);
    if(l.get(ii).getLoginName().equals(optionSelected[i])){
        System.out.println("in iteration");
        l.remove(ii)); // Remove user from the list
    } else {
        ++ii;
    }
}

List<User> l1=(List<User>) sess.getAttribute("allUserslist");
System.out.println("final size"+l1.size());
Maurice Perry
hey thankx it worked perfectly
sarah