What is the purpose and usage of @ModelAttribute in Spring MVC?

0 votes
112 views
asked Jun 16 in JAVA by admin (8,115 points)

Hi All

  What is the purpose and usage of @ModelAttribute in Spring MVC?

2 Answers

0 votes
answered Jun 16 by admin (8,115 points)

Hi 

  The @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view.

Let’s have a look at a quick example here to start understanding how this works:

@ModelAttribute

public void addAttributes(Model model) {

    model.addAttribute("msg", "Welcome to the Netherlands!");

}

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)

public String submit(@ModelAttribute("employee") Employee employee) {

    // Code that uses the employee object

    return "employeeView";

}

0 votes
answered Jun 16 by admin (8,115 points)

d

@ModelAttribute refers to a property of the Model object (the M in MVC ;) so let's say we have a form with a form backing object that is called "Person" Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute annotation:

public String processForm(@ModelAttribute("person") Person person){
    person.getStuff();
}

Check here for an example (Spring 2.5), also see "Using @ModelAttribute on a method argument" (Spring 3.1).

On the other hand the annotation is used to define objects which should be part of a Model. So if you want to have a Person object referenced in the Model you can use the following method:

@ModelAttribute("person")
public Person getPerson(){
    return new Person();
}

This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.

See "Using @ModelAttribute on a method" (Spring 3.1).

Hope this helped.

...