Saving form data in an object automatically
For forms directly related to a model object, for example, a form to add User
, the submitted form data can be automatically saved in an instance of that object.
How to do it…
In the controller method processing the form submission, add the object as an argument and make the field names in the JSP match its attributes:
Add a
User
argument annotated with@ModelAttribute
to the controller method processing the form submission:@RequestMapping(value="addUser", method=RequestMethod.POST) public void addUser(@ModelAttribute User user) { ...
In the JSP, make sure that the form fields correspond to the existing attributes of the object:
<form:input path="firstName" /> <form:input path="age" />
How it works…
When the form is submitted, this is what goes on behind the scenes:
A new
User
object is createdThe form values are injected into the object by matching the form field names to object attribute names, for example:
user.setFirstName(request.getParameter...