I'm working on a Spring Boot + Thymeleaf application where I have an edit page.
In my controller, I want to use different DTOs for the GET and POST methods:
ResponseDto for displaying data and RequestDto for updating data.
Here's my controller:
@GetMapping(EDIT_SOME_URL) public String editBoatEdition(@PathVariable final Long id, final Model model) { // editionService.getEditionById(id) returns ResponseEditionDto model.addAttribute(ENTITY_EDITION, editionService.getEditionById(id)); model.addAttribute(ENTITY_TEMPLATES, templateService.getAllTemplates()); return EDIT_ENTITY_EDITION_PAGE; } @PostMapping(EDIT_SOME_URL) public String updateBoatEdition(@Valid @ModelAttribute(ENTITY_EDITION) final RequestEditionDto dto, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { model.addAttribute(ENTITY_EDITION, dto); redirectAttributes.addFlashAttribute(ERROR, "Please correct the form below"); return EDIT_ENTITY_EDITION_PAGE; } final ResponseEditionDto responseEditionDto = editionService.updateEdition(dto); redirectAttributes.addFlashAttribute(SUCCESS, "Boat edition updated successfully!"); return "redirect://**" } But when I open the page, it fails with:
org.springframework.beans.NotReadablePropertyException: Invalid property 'templateId' of bean class [com.example.ResponseEditionDto] That makes sense, because in GET the model contains a ResponseEditionDto, but in POST I expect a RequestEditionDto.
My question:
- Is there a way to use different DTOs for GET and POST with the same @ModelAttribute name in a Thymeleaf form?
- Or do I need to always convert the ResponseDto into a RequestDto/UpdateDto before adding it to the model?
I’d prefer to keep my response and request objects separate, but I want to reuse the same form for both GET and POST.
I know I can use ModelMapper or manual conversion, but I’m wondering if there’s a built-in or cleaner way to make this pattern work without explicitly mapping between DTOs.