Expert Spring MVC and Web Flow

(Dana P.) #1

As you can see, this Validatorsimply checks whether the required fields have been set.
More complex constraints can be added as well. When a constraint is violated, the property
value is rejected by means of specifying the property name and a message code.


Declarative Validators


Currently two declarative validation strategies are available for Spring:



  • the Jakarta Commons Validator


•Valang

The Jakarta Commons Validatoruses an XML configuration file to declaratively specify
constraints. However, configuration is not intuitive, and its configuration format is very ver-
bose.
Valang, which stands for validation language, is a language specifically designed for
validating target objects. Its notation is concise and specifically targeted toward getting
data validated.
Valang is an open-source project and is available from Spring Modules. Go to
https://springmodules.dev.java.netto get a copy.
Rewriting the EasyAddressValidatorin Valang syntax is very easy, as shown in Listing 9-4.


Listing 9-4.Example of Declarative Constraint in Valang


{
location :? is not blank : 'Location must be specified' : 'addressLocationEmpty'
}


Each constraint written in Valang notation is enclosed in curly brackets (“{” and “}”).
Multiple constraints can be combined to create one Validator. The fields in a constraint are
separated with colons (“:”).
The first field in the constraint above is the property of the target object that’s being vali-
dated, and the second field is the actual constraint. This particular constraint tests whether
the location property is not blank. The question mark (“?”) replaces the property name speci-
fied in the first field to reduce typing.
When the evaluation of the constraint returns false, the property specified in field one
is rejected with the default message in field three. Field four contains the error code, which is
optional. If the error code cannot be found for the locale of the user or the default locale, the
default message will display.
A fifth optional field can contain error arguments. Note, though, that if error arguments
are provided, then an error code must be provided.
To create a Validatorfrom the constraint in Listing 9-5 Valang has to be configured in the
Spring ApplicationContext.
ValangValidatorFactoryBeanparses the Valang syntax once and creates a Validator
instance. Any performance overhead resulting from replacing Java validators with Valang is
thus limited to the one-time parsing of the syntax when the Spring ApplicationContextis
loaded. See Listing 9-5.


CHAPTER 9 ■VALIDATION 267
Free download pdf