The HttpSession interface provides several methods for managing session attributes.
These methods allow you to add, remove, retrieve, and enumerate attributes within the session scope.
Here are the core methods for managing session scope attributes:
void setAttribute(String name, Object value) throws IllegalStateException
void removeAttribute(String name) throws IllegalStateException
Object getAttribute(String name) throws IllegalStateException
Enumeration<String> getAttributeNames() throws IllegalStateException
-
void setAttribute(String name, Object value)
- name: The name of the attribute to be mapped to the object. This serves as the key for retrieving the attribute later.
- value: The object to be stored in the session. If this parameter is null
, the attribute will be removed from the session (equivalent to calling removeAttribute
).
- Throws IllegalStateException if the session has been invalidated.
- If an attribute with the same name already exists, its value will be replaced with the new value.
-
void removeAttribute(String name)
- name: The name of the attribute to remove from the session scope.
- Throws IllegalStateException if the session has been invalidated.
- If no attribute with the specified name exists, this method has no effect.
-
Object getAttribute(String name)
- Returns the object associated with the specified attribute name.
- Returns null
if no attribute with this name exists in the session scope.
- Throws IllegalStateException if the session has been invalidated.
- The returned object should be cast to the appropriate type when used.
-
Enumeration<String> getAttributeNames()
- Returns an enumeration containing the names of all attributes bound to the session.
- Returns an empty enumeration if no attributes exist in the session scope.
- Throws IllegalStateException if the session has been invalidated.
- This method is useful for iterating through all session attributes.