Forms
Chapter 6 had a recap of the generic work flow used by Spring when you submit a form to one
of your command Controllers. Let’s see how to link your Views to the command object and
the validation errors that Spring makes available for you through the JSP tag libraries.
Listing 8-6 shows a simple form from a JSTL view that takes advantage of the
<spring:bind>tag.
Listing 8-6.Binding to a Command Object Field in a JSTL View
<html>
<body>
<h1>Form Submission</h1>
<p>Please tell us your first name.</p>
<form action="" method="POST">
<spring:bind path="command.firstName">
<input type="text" name="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>" /><br>
<c:forEach var="error" items="${status.errorMessages}">
<c:out value="${error}"/><br>
</c:forEach>
</spring:bind>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Calling the <spring:bind>tag will cause an attribute of type BindStatusto be exposed to
your JSP. The status is instantiated for the field(s) on your command object denoted by the
path attribute you supply to the tag. The BindStatusclass is shown in Figure 8-2.
The first time you request the form in your browser with a GETrequest, the command
object will be empty, and the values for command.firstNameand status.errorMessageswill also
be empty. The code will then render the HTML for an empty form in response to this request.
The fun starts when you submit the form. If you submit a valid form—as determined by a
suitable Validatorclass for this particular command object—then the command object’s
firstNamefield is set to the value submitted by the user. This is immediately usable in your
Controllercode and you can pass the command object around in your service layer (or DAO
layer) safe in the knowledge that the values already meet the business validation that you
specified.
Should binding or validation fail, the default Controllerbehavior is to show the
form again in the browser. This time, the errors part of the status object will not be empty for
fields that failed and the code for the form shown above will now display these errors to your
user. The actual error messages are normally obtained from a MessageSourceobject in the
ApplicationContextfile. All the values that the user submitted originally will still be available
on the command object and will be redisplayed, so your user need only correct the fields for
which binding or validation failed. When binding failures do occur, the BindStatusvalues
contain exactly what was input by the user, regardless of the binding error, which acts as
the principal of least surprise for the user.
228 CHAPTER 8 ■SUPPORTED VIEW TYPES