Required body is missing in Thymeleaf template

Viewed 29

I am trying to update customers info with this method This is a classic update method where I take DTO as body and set the variables.

@RequestMapping(path = "/updateCustomerForm/{identityNumber}")
    public String updateCustomerForm(@PathVariable("identityNumber") String identityNumber,@RequestBody CustomerDTO customer){
        customerService.updateCustomer(identityNumber,customer);
        return "redirect:/customer/showList";
    }

This is my thymeleaf

 <form th:action="@{/customer/updateCustomerForm/*{identityNumber}}" th:object="${customer}" method="put">
    <input name="_method" type="hidden" value="put" />
    <input type="text" th:field="*{identityNumber}" placeholder="Enter identity number" class="form-control col-4 mb-4" />

    <input type="text" th:field="*{name}" placeholder="Enter name" class="form-control col-4 mb-4" />

    <input type="text" th:field="*{surname}" placeholder="Enter surname" class="form-control col-4 mb-4" />

    <input type="text" th:field="*{phoneNumber}" placeholder="Enter phone number" class="form-control col-4 mb-4" />

    <input type="text" th:field="*{salary}" placeholder="Enter salary" class="form-control col-4 mb-4" />

    <input type="text" th:field="*{age}" placeholder="Enter age" class="form-control col-4 mb-4" />

    <button class="btn btn-primary col-2" type="submit">Save</button>
    <input type="hidden" th:field="*{identityNumber}" />
  </form>

The error is required body is missing.

Can someone help with this topic?

1 Answers

Thymeleaf doesn't use JSON so you can't use @RequestBody to deserilize your message, since you are not getting JSON when you submit thymeleaf form. You can use @ModelAttribute to avoid handling each form fields manually. Thymeleaf and Spring let you bundle all of them together using annotation I just mentioned.

So, something like this:

@RequestMapping(path = "/updateCustomerForm/{identityNumber}")
    public String updateCustomerForm(@PathVariable("identityNumber") String identityNumber,@ModelAttribute CustomerDTO customer){
        customerService.updateCustomer(identityNumber,customer);
        return "redirect:/customer/showList";
    }

Shoud work as expected. For implementation details check this post

Related