Search code examples
spring-bootthymeleafpath-variablesget-mapping

Controller not processing Path Variable correctly - Spring boot


I have a list of customers who have some orders and I display them all in a table. I have added a button in order to delete each order if desired.

This is the table of how I display them.

<table id="customers">
        <tr>
            <th>Customer</th>
            <th>Order</th>
            <th>Action</th>
        </tr>
        <div th:each="customer : ${customers}">
          <tr>
            <td th:text="${customer.name}" style="font-weight: bold;"></td>
            <td></td>
            <td></td>
          </tr>
          <tr th:each="order : ${customer.orders}" >
            <td></td>
            <td th:text="${order.name}">
            <td>
                <a th:href="@{/manager/customer/{cid}(cid=${customer.id})/order/{oid}(oid=${order.id})}" class="button">Remove order</a>
            </td>
          </tr>
        </div>
</table>

In my Controller class I have the method where I process the deletion.

@GetMapping("/manager/customer/{cid}/order/{oid}")
    public String deleteCustomerOrder(@PathVariable(value="cid") Long cid, @PathVariable(value="oid") Long oid, Model model) {

        Customer c = customerService.findCustomerById(cid);
        //do stuff

        return "/manager/customerOrders";
    }

When I try to delete a specific order I get the following error

Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{cid}(cid=${customer.id})"

The path looks like this: http://localhost:8080/manager/customer/%7Bcid%7D(cid=$%7Bcustomer.id%7D)/order/2

Am I doing something wrong in the way that I get the IDs?


Solution

  • All parameters should be defined together. Change href as follows:

    <a th:href="@{/manager/customer/{cid}/order/{oid}(cid=${customer.id}, oid=${order.id})}" class="button">Remove order</a>
    

    See section Adding parameters in Thimeleaf documantation or in this tutorial