简体   繁体   中英

Required body is missing in Thymeleaf template

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM