Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 form is submitted, this is what goes on behind the scenes:

  • A new User object is created

  • The form values are injected into the object by matching the form field names to object attribute names, for example:

    user.setFirstName(request.getParameter...