Is Spring 3 @RequestMapping supposed to auto-bind request parameters?
-
28-04-2021 - |
Question
Auto-binding of request params seems like default behaviour, but I can't find a lot of documentation on it. Here is my example:
<form:form modelAttribute="test" action="testsubmit.do" method="POST">
Name: <form:input path="name" />
Nested Name: <form:input path="test.nestedName"/>
<input type="submit"/>
public class Test {
public String name;
public String name2;
public TestNested test;
...
public class TestNested {
public String nestedName;
...
Now with my mapping:
@RequestMapping(value = "/testsubmit")
public String testSubmit(Test test){
...
The test
object is binding the form values including the nested value. This seems to me like expected behavior, but I am a bit confused by the @ModelAttribute
annotation and its use with respect to objects specified as mapped method parameters.
15.3.2.8 Providing a link to data from the model with @ModelAttribute
says:
When you place it on a method parameter,
@ModelAttribute
maps a model attribute to the specific, annotated method parameter (see theprocessSubmit()
method below). This is how the controller gets a reference to the object holding the data entered in the form.
When I bind the object test
to the form on load, I set a value to name2
.
@RequestMapping(value = "/test")
public String test(Model model) {
Test test = new Test();
test.setName2("test name2");
model.addAttribute("test", test);
return "test";
}
This doesn't get passed through on the submit
method when I annotate the test
parameter with @ModelAttribute("test")
:
@RequestMapping(value = "/testsubmit")
public String testSubmit(@ModelAttribute("test") Test test) {
...
This is expected to me as name2
was not specified as a form field/request param, but it doesn't help me understand the point of the @ModelAttribute("test")
usage. Can anyone shed some light on this for me?
La solution
@ModelAttribute just lets you specify a different name/key for your object in the model. If you don't use it, Spring will automatically assign a name based on the object's class, e.g. "test" in the case of your "Test" class. With @ModelAttribute you could change the name/key of your object in the model to, for example, "whatever" by specifying "@ModelAttribute("whatever")".