Search code examples
javaspringspring-mvcmodelattribute

Spring @ModelAttribute shouldn't add the attribute to view?


As far I understood, @ModelAttribute annotation is used to put an attribute right to view model. I've found official Spring guide called Handling form submission and there's an example of simple controller with @ModelAttribute:

@Controller
public class GreetingController {

    @RequestMapping(value="/greeting", method=RequestMethod.GET)
    public String greetingForm(Model model) {
        model.addAttribute("greeting", new Greeting());
        return "greeting";
    }

    @RequestMapping(value="/greeting", method=RequestMethod.POST)
    public String greetingSubmit(@ModelAttribute Greeting greeting, Model model) {
        model.addAttribute("greeting", greeting);
        return "result";
    }

}

Why in the last method the model attribute added manually? Shouldn't it to be already there due to @ModelAttribute?


Solution

  • When you use @ModelAttribute in a method that return a value, Spring add that value to the Model an you can after use it in the view.

    @ModelAttribute("countries")
    public List findAllCountries() {
       return countryService.findAllCountries();
    }
    

    But if you use it like a method param in a method annotated with requestMapping, Spring will asociate the form in the jsp page. In this code

    @RequestMapping(value="/greeting", method=RequestMethod.POST)
    public String greetingSubmit(@ModelAttribute Greeting greeting, Model model)    {
        model.addAttribute("greeting", greeting);
        return "result";
    }
    

    You are getting the form values so you need to add it to the Model in order to use the value in the view.