Tapping Into User Context

Learn how to make our application user-specific by adding user context to the web page.

An essential requirement of security management is that we have access to the current user’s details. Throughout this course, presuming we’ve followed the examples, the cart’s name has simply been My Cart.

Making the shopping cart user-specific

With the user login details, we can suddenly support a different cart for every user. The code below shows how to do just that:

@GetMapping
Mono<Rendering> home(Authentication auth) { // 1
return Mono.just(Rendering.view("home.html")
.modelAttribute("items", this.inventoryService.getInventory())
.modelAttribute("cart", this.inventoryService.getCart(cartName(auth)) // 2
.defaultIfEmpty(new Cart(cartName(auth))))
.modelAttribute("auth", auth) // 3
.build());
}
Making the shopping cart user-specific

Here’s a breakdown of the code above:

  1. In line 2, we add Authentication as another parameter to the home() method so that Spring ...

Get hands-on with 1400+ tech skills courses.