import org.springframework.validation.Validator;
import com.apress.prospring3.ch14.domain.Contact;
@Component("contactValidator")
public class ContactValidator implements Validator {
public boolean supports(Class<?> clazz) {
return Contact.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "firstName", "firstName.empty");
}
}
As shown in Listing 14-16, the validator class implements the Validator interface and implements
two methods. The supports() method indicates whether validation of the passed-in class type is
supported by the validator. The validate() method performs validation on the passed-in object. The
result will be stored in an instance of the org.springframework.validation.Errors interface. In the
validate() method, we perform a check only on the firstName attribute and use the convenient
ValidationUtils.rejectIfEmpty() method to ensure that the first name of contact is not empty. The last
argument is the error code, which can be used for looking up validation messages from resource bundles
for displaying localized error messages.
Listing 14-17 shows the Spring configuration file (spring-validator-app-context.xml).
Listing 14-17. Configuration for Spring Validator
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.apress.prospring3.ch14.validator"/>
</beans>
Listing 14-18 shows the testing program for the validator class.
Listing 14-18. Testing Spring Validator
package com.apress.prospring3.ch14.validator;
import java.util.List;
import
org.springframework.context.support.GenericXmlApplicationContext;
import
org.springframework.validation.BeanPropertyBindingResult;
import
org.springframework.validation.ObjectError;
import
org.springframework.validation.ValidationUtils;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home