0

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:

  1. Is there a way to use different DTOs for GET and POST with the same @ModelAttribute name in a Thymeleaf form?
  2. 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.

1 Answer 1

0

The object passed in the model under the attribute name ENTITY_EDITION should not matter as such as long as you are handling it correctly on the html.

The exception indicates spring is failing to read the templateId property from the ResponseEditionDto. I suspect the field templateId or its getter getTemplateId method is missing from the ResponseEditionDto .

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.