1. import io.micronaut.http.annotation.Get
    2. import io.micronaut.http.annotation.Post
    3. import io.micronaut.session.Session
    4. import io.micronaut.session.annotation.SessionValue
    5. import javax.annotation.Nullable
    6. import javax.validation.constraints.NotBlank
    7. @Controller("/shopping")
    8. class ShoppingController {
    9. Cart addItem(Session session, @NotBlank String name) { (2)
    10. Cart cart = session.get(ATTR_CART, Cart.class).orElseGet({ -> (3)
    11. Cart newCart = new Cart()
    12. session.put(ATTR_CART, newCart) (4)
    13. newCart
    14. })
    15. cart.getItems().add(name)
    16. cart
    17. }
    18. }

    Note that because the is declared as a required parameter to the execute the controller action, the Session will be created and saved to the .

    Using @Nullable with Sessions

    1. @Post("/cart/clear")
    2. void clearCart(@Nullable Session session) {
    3. if (session != null) {
    4. session.remove(ATTR_CART);
    5. }
    6. }

    Using @Nullable with Sessions

    1. @Post("/cart/clear")
    2. internal fun clearCart(session: Session?) {
    3. session?.remove(ATTR_CART)