Annotation Interface SessionAttribute


@Target(PARAMETER) @Retention(RUNTIME) @Documented public @interface SessionAttribute
Annotation to bind a method parameter to a session attribute.

The main motivation is to provide convenient access to existing, permanent session attributes (e.g. user authentication object) with an optional/required check and a cast to the target method parameter type.

For use cases that require adding or removing session attributes consider injecting org.springframework.web.context.request.WebRequest or jakarta.servlet.http.HttpSession into the controller method.

For temporary storage of model attributes in the session as part of the workflow for a controller, consider using SessionAttributes instead.

Since:
4.3
Author:
Rossen Stoyanchev
See Also:
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    The name of the session attribute to bind to.
    boolean
    Whether the session attribute is required.
    Alias for name().
  • Element Details

    • value

      @AliasFor("name") String value
      Alias for name().
      Default:
      ""
    • name

      @AliasFor("value") String name
      The name of the session attribute to bind to.

      The default name is inferred from the method parameter name.

      Default:
      ""
    • required

      boolean required
      Whether the session attribute is required.

      Defaults to true, leading to an exception being thrown if the attribute is missing in the session or there is no session. Switch this to false if you prefer a null or Java 8 java.util.Optional if the attribute doesn't exist.

      Default:
      true