javaservletshttpsession

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%");


Solution

  • You can go through attribute names with stream:

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