Using @SessionValue
Rather than explicitly injecting the Session into a controller method you can instead use @SessionValue. For example:
Using @SessionValue
@Get("/cart")
@SessionValue(ATTR_CART) (1)
Cart viewCart(@SessionValue @Nullable Cart cart) { (2)
if (cart == null) {
cart = new Cart();
}
return cart;
}
Using @SessionValue
@Get("/cart")
@SessionValue("cart") (1)
Cart viewCart(@SessionValue @Nullable Cart cart) { (2)
if (cart == null) {
cart = new Cart()
}
cart
}
Using @SessionValue
@Get("/cart")
@SessionValue(ATTR_CART) (1)
internal fun viewCart(@SessionValue cart: Cart?): Cart { (2)
var cart = cart
if (cart == null) {
cart = Cart()
}
return cart
}
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. |