img
For example, a user enters some contact information via the web application within the browser
and then submits the data to the server. On the server side, if the web application was developed in
Spring MVC, Spring will extract the data from the HTTP request and perform the conversion from a
String to the desired type based on the formatting rule (for example, a String representing a date will be
converted into a Date field, with the formatting rule yyyy-MM-dd). The process is called data binding.
When the data binding is complete and the domain object constructed, validation will then be applied to
the object, and any errors will be returned and displayed to the user. If validation succeeds, the object
will be persisted to the database.
Figure 14-2 shows the process.
Figure 14-2. Relationship between validation, conversion, and formatting
Spring supports two main types of validation. The first one is provided by Spring, within which
custom validators can be created by implementing the org.springframework.validation.Validator
interface. The other one is via Spring's support of JSR-303, the Bean Validation API. We will go through
both of them in the coming sections.
Using Spring Validator Interface
Using Spring's Validator interface, we can develop some validation logic by creating a class to
implement the interface.
Let's see how it works. For the Contact class that we've worked with so far, suppose the first name
cannot be empty. To validate Contact objects against this rule, we can create a custom validator. Listing
14-16 shows the validator class.
Listing 14-16. The ContactValidator Class
package com.apress.prospring3.ch14.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home