import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import io.micronaut.session.Session
import io.micronaut.session.annotation.SessionValue
import javax.annotation.Nullable
import javax.validation.constraints.NotBlank
@Controller("/shopping")
class ShoppingController {
Cart addItem(Session session, @NotBlank String name) { (2)
Cart cart = session.get(ATTR_CART, Cart.class).orElseGet({ -> (3)
Cart newCart = new Cart()
session.put(ATTR_CART, newCart) (4)
newCart
})
cart.getItems().add(name)
cart
}
}
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
@Post("/cart/clear")
void clearCart(@Nullable Session session) {
if (session != null) {
session.remove(ATTR_CART);
}
}
Using @Nullable with Sessions
@Post("/cart/clear")
internal fun clearCart(session: Session?) {
session?.remove(ATTR_CART)