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:

  1. 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) {
    ...
  2. 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 ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.