Troubleshoot Delete Product Endpoint

Let’s troubleshoot our problem by digging into the “Controller” portion of our MVC model to see why our delete request isn’t working. Navigate to the Cloud9 service and open the IDE for this workshop. With the source tree that appears on the left, navigate to the “lab 1/server/src” folder. Within the nested folders (these correspond to Java’s package naming organization of code), select the “controller” folder. This will give you a list of the controllers that are implemented for our monolith. Select the “ProductsController.java” file to open the editor for this file.

Within this file, we’ll navigate to the updateProduct() and deleteProduct() methods of our Java class. These two methods represent the entry point of our HTTP calls that will be processed by the various methods in this class. You’ll notice that, within the body of these methods, we are calling the actual product service that is the actual implementation of our service functionality. Let’s take a closer look at these two specific methods to see if we can figure out what’s broken with the delete product functionality that we observed in the application. The two methods are as follows:

@PostMapping("/updateProduct")
public String updateProduct(@ModelAttribute Product product, BindingResult bindingResult, Model model) throws Exception {
    LOGGER.info("ProductsController::updateProduct " + product);
    if (bindingResult.hasErrors()) {

    }
    model.addAttribute("product", product);

    product = productService.saveProduct(product);
    return "redirect:/products";
}

public String deleteProduct(@ModelAttribute Product product) throws Exception {
    LOGGER.info("ProductsController::deleteProduct " + product.getId());
    productService.deleteProduct(product);
    return "redirect:/products";
}

At first glance, there doesn’t appear to be anything wrong without deleteProduct() method. However, if you compare it to the updateProduct() method above it, you’ll notice that an @PostMapping annotation is associated with our updateProduct() method. This annotation is missing from our deleteProduct() method. Without this annotation, there’s our HTTP calls will have no routing to the delete method.

To resolve this, we’ll need to simply add the missing annotation to our deleteProduct() method. Do this by adding the annotation as shown below:

@PostMapping("/deleteProduct")
public String deleteProduct(@ModelAttribute Product product) throws Exception {
    LOGGER.info("ProductsController::deleteProduct " + product.getId());
    productService.deleteProduct(product);
    return "redirect:/products";
}