Expert Spring MVC and Web Flow

(Dana P.) #1

Validation


Command objects that have been populated by DataBindercan be validated and report back
errors when validation fails. Spring offers its own validation infrastructure as an add-on to
core Spring. In fact, validation is not even considered part of Spring MVC.
Validators are implementations of the org.springframework.validation.Validatorinter-
face. They are stateless singleton classes that are configured in the Spring ApplicationContext
and injected into your Controllers and test objects and their property values.
Validators are stateless objects just like Spring MVC Controllers. The Validatorinterface
is designed to facilitate usage in a thread-safe manner; implementation classes should make
sure they are thread-safe as well.
Two types of Validatorimplementations exist:


•Programmatic Validators where validation constraints are coded

•Declarative Validators that create validation constraints based on configuration

Programmatic Validators


The Validatorinterface has two methods that should be implemented. Refer to Listings 9-1
and 9-2.


Listing 9-1.org.springframework.validation.Validator Interface


public interface org.springframework.validation.Validator {
public boolean supports(Class clazz);
public void validate(Object target, Errors errors);
}


The validate()method implements the actual constraints on the target object. The
supports()method defines which classes the Validatorsupports.
The org.springframework.validation.Errorsinterface is key to the Spring validation
infrastructure. The Errorsinterface is discussed at the end of this chapter. Implementation
classes of this interface register errors that occur when binding and validating objects. The
instance received by the validate()method has to be populated with errors detected when
testing the constraints on the target objects.
To reject a property value use one of the rejectValue()methods of the Errorsinterface.


265

CHAPTER 9


■ ■ ■

Free download pdf