Search⌘ K
AI Features

Showing the Cart

Explore how to show the shopping cart on a web page within a Spring Boot application. Learn to inject reactive repositories, use WebFlux with Thymeleaf templates, and display inventory and cart items dynamically. Understand form handling and configuration to support DELETE operations in a reactive environment.

Showing the cart on the web page

Before we start manipulating the cart, it would be useful to show it on the web page.

For this, we need to retool ourHomeController. To do that, we first need to inject our new repositories:

Java
@Controller //1
public class HomeController {
private ItemRepository itemRepository;
private CartRepository cartRepository;
public HomeController(ItemRepository itemRepository, CartRepository cartRepository) { //2
this.itemRepository = itemRepository;
this.cartRepository = cartRepository;
}
...
}
HomeController getting repositories via constructor injection

Here’s the breakdown of the code written above:

  1. In line 1, @Controller signals this as a Spring Web controller that serves up templated views.

  2. In line 6, the constructor is used by Spring to inject the itemRepository and the cartRepository. This is known as constructor injection, and it is a highly recommended tactic by the Spring team.

We can post a more sophisticated listing of our inventory and the cart with this in place. ...