Magiranu
Magiranu

Reputation: 309

Confused with naming convention for Springs @ModelAttribute annotation

The official documentation doens't answer my question fully and I kindly ask for your help.

Is is true that the name of the @ModelAttribute has to be the same as the actual object Pet pet (a)? Or can it also be different (b)?

@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
(a) public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult r) {
(b) public String processSubmit(@ModelAttribute("cat") Dog rex, BindingResult r 
    if (r.hasErrors()) {
        return "petForm";
    }
    // ...
}

Upvotes: 0

Views: 169

Answers (1)

iagooa
iagooa

Reputation: 42

It may be different, the name of @ModelAttribute must match the attribute that It is used in the view. If you do not indicate the name, Spring take the name of the variable by default.

Upvotes: 1

Related Questions