I am working on a project made with Spring Framework. I have not touched Java in years, and this is all very new to me. The project has the below UI controller displaying product information:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
import java.util.ArrayList;
@Controller
public class UiController {
private ProductService productService;
private LocationService locationService;
private InventoryService inventoryService;
private CartService cartService;
public UiController(
ProductService productService,
LocationService locationService,
InventoryService inventoryService,
CartService cartService) {
this.productService = productService;
this.locationService = locationService;
this.inventoryService = inventoryService;
this.cartService = cartService;
}
@GetMapping("/")
public String home(Model model) {
model.addAttribute("products", productService.getAllProducts());
return "index";
}
@GetMapping("/brand/{brand}")
public String brand(Model model, @PathVariable String brand) {
model.addAttribute("products", productService.getProductByBrand(brand));
return "index";
}
@GetMapping("/product/{productId}")
public String product(Model model, @PathVariable String productId) {
Product prod = productService.getProduct(productId);
ArrayList<Product> ps = new ArrayList<Product>();
ps.add(prod);
model.addAttribute("products", ps);
return "index";
}
}
To go with this controller, I have an html template:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Product Listing</h1>
<table>
<tr>
<th>PRODUCT ID</th>
<th>PRICE</th>
<th>DESCRIPTION</th>
<th>BRAND</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.getProductId()}"/>
<td th:text="${product.getPrice()}"/>
<td th:text="${product.getDescription()}"/>
<td th:text="${product.getBrand()}"/>
</tr>
</table>
</body>
</html>
When there are no products - meaning that if the size()
of my ArrayList
products
is 0, I want to display 404.
How could I do this?