I need some clarification about Spring 3.0 MVC and @ModelAttribute annotated method parameter. I have a Controller which looks like this one:
RequestMapping(value = "/home")
@Controller
public class MyController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView foo() {
// do something
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView bar(
@ModelAttribute("barCommand") SomeObject obj) {
// do sometihng with obj and data sent from the form
}
}
and on my home.jsp i have a form like this one which sends his data to the RequestMethod.POST method of MyController
<form:form action="home" commandName="barCommband">
</form:form
Now if i try to access home.jsp i get this Exception:
java.lang.IllegalStateException:
Neither BindingResult nor plain target object for bean name 'barCommand' available as request attribute
To resolve this i found that i need to add the
@ModelAttribute("barCommand") SomeObject obj
parameter to the Request.GET method of MyController, even if i won't use obj in that method. And for example if add another form to home.jsp with a different commandName like this:
<form:form action="home/doSomething" commandName="anotherCommand">
</form:form
i also have to add that parameter on the RequestMethod.GET, which will now look like:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView foo( @ModelAttribute("barCommand") SomeObject obj1,
@ModelAttribute("anotherCommand") AnotherObj obj2) {
// do something
}
or i get the same exception. What i'm asking is if this is a normal Spring 3 MVC behaviour or if i'm doing something wrong. And why do i need to put all the @ModelAttribute parameters on the RequestMethod.GET method?
Thanks in advance for you help
Stefano
Here is the spring mvc reference. Looked through it briefly and found 2 approaches:
You may use first to customize data binding and, thus, create command objects on-the-fly. Second allows you to annotate method with it and prepopulate model attributes with this name:
@ModelAttribute("bean_name")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
I hope it will populate model attributes with name 'bean_name' if it is null.