Using @SessionValue

Rather than explicitly injecting the Session into a controller method you can instead use @SessionValue. For example:

Using @SessionValue

  1. @Get("/cart")
  2. @SessionValue(ATTR_CART) (1)
  3. Cart viewCart(@SessionValue @Nullable Cart cart) { (2)
  4. if (cart == null) {
  5. cart = new Cart();
  6. }
  7. return cart;
  8. }

Using @SessionValue

  1. @Get("/cart")
  2. @SessionValue("cart") (1)
  3. Cart viewCart(@SessionValue @Nullable Cart cart) { (2)
  4. if (cart == null) {
  5. cart = new Cart()
  6. }
  7. cart
  8. }

Using @SessionValue

  1. @Get("/cart")
  2. @SessionValue(ATTR_CART) (1)
  3. internal fun viewCart(@SessionValue cart: Cart?): Cart { (2)
  4. var cart = cart
  5. if (cart == null) {
  6. cart = Cart()
  7. }
  8. return cart
  9. }
1@SessionValue is declared on the method resulting in the return value being stored in the Session. Note that you must specify the attribute name when used on a return value
2@SessionValue is used on a @Nullable parameter which results in looking up the value from the Session in a non-blocking way and supplying it if present. In the case a value is not specified to @SessionValue resulting in the parameter name being used to lookup the attribute.