简体   繁体   中英

Remove session attributes which name starts from specific name

In my servlet, if I want to remove a specific session attribute I run:

session.removeAttribute("user");

and I want to remove all of them:

session.invalidate();

How to remove only those session attributes which their name starts from a specific value? For example instead running:

session.removeAttribute("userDsdf");
session.removeAttribute("userSDFSF");
session.removeAttribute("userVSDfs");
session.removeAttribute("userESFDFS");

run something like session.removeAttribute("user%");

There's no method to do that work exactly, but you can do it yourself by enumerating attributes and filtering:

Enumeration<String> attributes = session.getAttributeNames();
while (attributes.hasMoreElements()) {
    String next = attributes.nextElement();
    if (!next.startsWith("user")) continue;
    session.removeAttribute(next);
}

You can go through attribute names with stream:

Collections.list(session.getAttributeNames()).stream()
        .filter(a -> a.startsWith("user"))
            .forEach(a -> session.removeAttribute(a));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM