In this tutorial you will learn about the @ModelAttribute Annotaion
In this tutorial you will learn about the @ModelAttribute Annotaion@ModelAttribute annotation can be used for maintaining some common attributes for all the handler methods inside the class, rather than adding attributes for on model in each handler methods. you can also use this annotation inside the handler method parameter. you may use this annotaion as
@ModelAttribute("cities") public ListchangeData() { List cities = new ArrayList (); cities.add("Patna"); cities.add("Delhi"); cities.add("Kanpur"); cities.add("Lucknow"); cities.add("Hyderabad"); cities.add("Merath"); return cities; }
A sample controller class is given below
MyController.java
package roseindia.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import roseindia.form.SampleForm; @Controller public class MyController { @RequestMapping(value = "/load-form") public String loadform(@ModelAttribute("sampleForm") SampleForm sampleForm) { return "index"; } @RequestMapping(value = "/view-attributes") public String modelAttributeExample( @ModelAttribute("sampleForm") SampleForm sampleForm) { return "view-data"; } /* * Set Model Default attribute here. */ @ModelAttribute("cities") public ListchangeData() { List cities = new ArrayList (); cities.add("Patna"); cities.add("Delhi"); cities.add("Kanpur"); cities.add("Lucknow"); cities.add("Hyderabad"); cities.add("Merath"); return cities; } }
You can download the complete source code from here