Building a Form

Problem

How to build a form to collect data entered by user?  How to bind the data entered by user to Spring's form backing object?  How to do validation on data entered by user?  How to display error messages back to the user?  How to prevent form double submit?  How to bind collections?

Pre-requisite

Solution

Before we begin, let's get some verbage out of the way.

Domain Object

This is a POJO that corresponds to your web application's business domain language.  It contains data and logic.  For example, a Car object will have attribute data such as Year, Make, and Model.  It might also have a logic like the startEngine method.

Form Backing Object/Command Object

This is a POJO that is used to collect all information on a form.  It contains data only.  It is also called a Command Object in some Spring tutorials.  For example, an add a new car form page will have a Car form backing object with attribute data such as Year, Make and Model.  You'll notice that it contains the same attributes as a domain object, thus typically, your domain object can double as a form backing object.

ModelAttribute

These are data that is passed into a page.  It's essentially a Map with name/object pair.  Obviously, one of the ModelAttribute will be the form backing object.  In addition, several ModelAttribute objects can be used to passing other data that is used for displaying the page.  For example, values for a drop down list used in a form.

Property Editor

There are used to converting text on a form to the desired java objects.  Spring MVC automatically binds int, long, and provides custom binders for dates.  You can build your own custom property editor to bind, for example, an employee id to an Employee domain object.

Validator

Java classes that contains validation logic to invalidate a form backing object that contains data entered by the user.


Form Basics

We'll build a form that collects student contact information. In this guide we'll show to to

  • display a form
  • process a form
  • collect data entered by the user
  • bind the data to a form backing object
  • validate the data entered by the user
  • display the error messages

Form with Collections

Sometimes a form can contain collections such as lists or maps.  We'll show you how to

  • bind static list or map to a form backing object
  • bind dynamic list to a form backing object