In this period I am studying the Sping MVC showcase example dowlodable form STS dashboard.
In the Request Data section is shown how to bind the parameter of an HTTP GET Request to the homonymous variables of a JavaBean.
In practice I have the following link:
<a id="group" class="textLink"
href="<c:url value="/data/group?param1=foo¶m2=bar¶m3=baz" />">
Group of query parameters
</a>
This link generate a GET HTTP Request towards the “/data/group” URL. This request carries 3 parameter named param1, param2, param3.
This request is handled by the following method of my controller class:
@RequestMapping(value="group", method=RequestMethod.GET)
public @ResponseBody String withParamGroup(JavaBean bean) {
return "Obtained parameter group " + bean;
}
The withParamGroup() method thake a JavaBean object that is only an object that contains 3 variables and getters/setters methods, something like this:
public class JavaBean {
private String param1;
private String param2;
private String param3;
// GETTER & SETTER method
}
So the param1 parameter in the HTTP Request is stored in the param1 variable of the JavaBean Object, and the same thing for param2 and param3.
Ok…I think that this is clear for me…but…who does this operation? Is it automatically made by Spring framework?
Why I have not to use something like @RequestParam annotation as I do when I bind a single HTTP Request parameter with a single variable in the controller method?
Another doubt is: the HTTP parameters names have to be the same of the JavaBean variables or simply the first parameter value is stored in the first variable of the JavaBean object?
Thanks
Andrea
Interestingly the Spring documentation appears to be somewhat short on details about this feature, but there are some points in the Spring MVC documentation which seems to indicate that Spring is responsible for applying this behavior during the request mapping process. There is a reference to this ability in a section in the documentation on using the
@RequestParamattribute to bind request parameters to method parameters (located here):If you then go to the section referenced, the documentation suggests that primitive object types are converted automatically by Spring (here):
Unfortunately this does not seem to give an adequate explanation for why non-primitive object types are being converted, but perhaps the documentation is not current with the capabilities.
To your final point on whether or not the attribute names must match the parameters – this is conjecture as I cannot find any documentation to support it, but I would guess based on the behavior your are experiencing with this “feature” that Spring will look to match the parameters to attributes by name rather than order of parameters on the request.