Search code examples
javaspringspring-mvcthymeleafspring-form

How to set up Spring Form and Thymeleaf to not changing the fields of object added as model attribute if the form inputs not explicitly use it?


If I have the DTO object, added as attribute model in controller. It has two business fileds, say

public class Owner {
    private Long id;

    private String firstName;
    private String secondName;
}

in some spring form I'd like to change the first name only still using the Owner as DTO, and this form doesn't have the second name input at all. And I also don't want to place the second name to the form as hidden input for privacy reasons, for example, so I have the only input dealing with the first name in the form? Is there a way to place the DTO to the model with both first and second name and in the @PostMapping controller method still getting both first and second name in the @ModelAttribute parameter object of the method? i'm getting the second name null in this case.


Solution

  • If the model was added to model attribute via addAttribute("owner", owner), @SessionAttribute("owner") annotation over the @Controller-marked class together with using @ModelAttribute("owner") ownet in the controller method parameter is the decision that helps. With @SessionAttribute the data is not cleared by the form with all fields put to null values.

    Explicit naming of @ModelAttribute("named_via_here") being the same as @SessionAttribute("named_via_here") is required (it may work without it, but not guaranteed)