Validators and Business Logic
Validators are related to the presentation layer. However, if objects that are validated by a
Validatorare passed on to the business logic, this Validatorcan also be considered as part of
the business logic layer.
Constraints can be called or implemented in three places:
- Validators
- service objects
•a validation method on domain classes
Validators are the only truly pluggable option. They can be injected into Controllers that
call the business logic. Business logic has to implement second-level coarse-grained constraints,
probably by throwing business exceptions. Validators handle the first-level validation that’s
more fine-grained, supports internalization, and is fully integrated with the presentation layer
through the Errorsinterface. These are the most important advantages Validators offer over
other alternatives.
Errors Interface
The Errorsinstance received by the validate method of the Validatorinterface is actually an
instance of BindException. These two classes serve to report validation errors on the target
being validated.
Two error types can be distinguished:
•Errors related to the object itself
•Errors related to missing or invalid property values
To reject an object as a whole, use the reject()methods (see Listing 9-21).
Listing 9-21.reject() Methods in the org.springframework.validation.Errors Interface
public void reject(String errorCode);
public void reject(String errorCode, String defaultMessage);
public void reject(String errorCode, Object[] errorArguments, String
defaultMessage);
Rejecting an object as a whole is called a global error, because though no specific property
value is invalid, the form values cannot be processed. An example could be a customer who is
underage.
When property values are invalid or required properties are missing, the rejectValue()
methods can be used, as shown in Listing 9-22.
CHAPTER 9 ■VALIDATION 279