Software Company
Software Company

Reputation: 151

How does @ModelAttribute send data to jsp

I have a query. I am using @ModelAttribute on a function in a formController.

@ModelAttribute("modelAttrVar")
public ModelAttr function(){
    ModelAttr obj = new ModelAttr();
    //...code
    return obj;
}

But this model attribute is not added to the ModelAndView I am returning.....

public ModelAndView func2(){
    ModelAndView obj = new ModelAndView();
    obj.addAttribute("variableName" , value);
    obj.setViewName("viewName");
    return obj;
}

Now when I see the jsp then the model Attribute variable modelAttrVar is available in jsp and is giving values. How ??

Please Help!!

Upvotes: 1

Views: 9540

Answers (1)

daN
daN

Reputation: 101

There's something not clear!

The @ModelAttribute annotation is used to bind a form inside a jsp to a controller, in order to have all the fields, written inside an html form, available in a Controller.

What is @ModelAttribute in Spring MVC?

So basically a method annotated with @ModelAttribute should be work as landing point method, after a post request (form submit).

So let's take an example, you have a POJO with two variable:

public class ModelAttrExample {

String name;
String lastName;

///getter and setter...
}

a JSP indexForm.jsp

<form:form action="/greeting" >
 <form:input path="name" />
 <form:input path="lastName" />

 <input type="submit" value="Submit" />
</form:form>

and a SpringController

@Controller
public class GreetingController {

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

@RequestMapping(value="/greeting", method=RequestMethod.POST)
public String greetingSubmit(@ModelAttribute ModelAttrExample example, Model model) {

   example.getName();//same form value
   example.getLastName(); //same form value
   //do your logic here...
   }
}

Once the form is submitted the greetingSubmit() method is triggered, and an instance of the ModelAttrExample, filled with the datas of the form, will be available inside the method.

so... @ModelAttribute is used to take the values from a html form field and put this datas inside an class instance variables.

I suggest you to follow this tutorial from Spring, It is very well written and very easy to understand

If you need more info do not hesitate to ask :)

Upvotes: 2

Related Questions