Book Image

SPRING COOKBOOK

By : Jerome Jaglale, Yilmaz
Book Image

SPRING COOKBOOK

By: Jerome Jaglale, Yilmaz

Overview of this book

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.
Table of Contents (14 chapters)
13
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...