import org.springframework.validation.Validator;
import com.apress.prospring3.ch14.domain.Contact;
public class SpringValidatorSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring-validator-app-context.xml");
ctx.refresh();
Contact contact = new Contact();
contact.setFirstName(null);
contact.setLastName("Ho");
Validator contactValidator = ctx.getBean(
"contactValidator", Validator.class);
BeanPropertyBindingResult result =
new BeanPropertyBindingResult(contact, "Clarence");
ValidationUtils.invokeValidator(contactValidator, contact, result);
List<ObjectError> errors = result.getAllErrors();
System.out.println("No of validation errors: " + errors.size());
for (ObjectError error: errors) {
System.out.println(error.getCode());
}
}
}
As shown in Listing 14-18, a Contact object is constructed with first name set to null. Then, the
validator is retrieved from the ApplicationContext. To store the validation result, an instance of
BeanPropertyBindingResult class is constructed. To perform the validation, the
ValidationUtils.invokeValidator() method is called. Then we check for validation errors.
Running the program produces the following output:
No of validation errors: 1
firstName.empty
The validation produces one error, and the error code is displayed correctly.
Using JSR-303 Bean Validation
In Spring 3, full support for the JSR-303 Bean Validation API was introduced. The Bean Validation API
defines a set of constraints in the form of Java annotations (for example, @NotNull) under the package
javax.validation.constraints that can be applied to the domain objects. In addition, custom validators
(for example, class-level validators) can be developed and applied using annotation.
Using the Bean Validation API frees you from coupling to a specific validation service provider. By
using the Bean Validation API, you can use standard annotations and the API for implementing
validation logic to your domain objects, without knowing the underlying validation service provider. For
example, the Hibernate Validator (http://hibernate.org/subprojects/validator) is a popular JSR-303
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home