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%");
CodePudding user response:
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);
}
CodePudding user response:
You can go through attribute names with stream:
Collections.list(session.getAttributeNames()).stream()
.filter(a -> a.startsWith("user"))
.forEach(a -> session.removeAttribute(a));