Understanding the concept of data binding in a Spring-MVC app
I'm trying to understand the concept of data binding in Spring-MVC with Velocity (I'm learning this framework and porti开发者_Go百科ng an app to this platform).
I'm used to getting form variables using request.getParameter("username")
, in the Spring world it seems that I can perform validation and such against "form objects" e.g. a datamodel style object that represent all the fields of a form.
The concept of a validator makes sense, but marshaling the data from a query string to these objects is fuzzy for me still. This is the concept of "Data Binding" correct?
If I'm correct to this point a few specific questions:
- When a "binding" is made between a form variable (say
"username"
for example) and the the field of an object (sayorg.a.b.MyNewUserFormObj.username
) is that "binding" a permanent definition such that all subsequent http posts of that form cause theusername
form variable to be assigned toorg.a.b.MyNewUserFormObj.username
? - How in the world do I accomplish the above binding definition? (if what I've said up to now is correct I feel like Costello in 'Who's on First', I don't even know what I just said!), I just need a conceptual picture.
Thanks for setting straight a brain gone astray.
There is no magic in data binding.
Actually, Spring simply populate properties of @ModelAttribute
object with the values of request parameters with the corresponding names (in the simpliest case request parameter have the same name as a property, but nested properties are also supported).
So, if you have
<input type = "text" name = "firstName" />
and
public class Person {
private String firstName;
... getters, setters ...
}
you get a value from the form field.
Spring also provides convenient method for creating HTML forms. So, instead of creating form fields manually, you can write in JSP:
<form:form modelAttribute = "person" ...>
<form:input path = "firstName" />
</form:form>
or in Velocity (note that in this case <form>
is created manually and property path is prefixed with the model attribute name):
<form ...>
#springFormInput("person.firstName" "")
</form>
Fields of the forms generated this way will be prepopulated with the values of the corresponding properties of the model attribute (that's why model attribute name is needed).
精彩评论