Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 9-22.rejectValue() Methods in the org.springframework.validation.Errors Interface

public void rejectValue(String propertyName, String errorCode);
public void rejectValue(String propertyName, String errorCode, ➥
String defaultMessage);
public void rejectValue(String propertyName, String errorCode, Object[] ➥
errorArguments, String defaultMessage);

Rejecting a property value is called a field error. Types of field errors include invalid values
of any kind, nullvalues for required properties, and Stringvalues containing only white-space
characters.
Global errors typically appear on top of a form in the view, while field errors typically
appear next to the input fields they are related to.
The Errorsinterface supports nested Validators. This allows you to reuse Validators for a
single class to validate object graphs. Two methods on the Errorsinterface allow you to man-
age the nested path. The nested path defines the path to the object that is rejected (or its
property values).
CustomerValidatordispatches control to the AddressValidatorto validate the address prop-
erty. Before delegating, the CustomerValidatorchanges the nested path. Refer to Listing 9-23.

Listing 9-23.Example of Using Nested Path to Delegate to Other Validator

package com.apress.expertspringmvc.validation;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import com.apress.expertspringmvc.Customer;
import org.apache.commons.lang.StringUtils;

public class CustomerValidator implements Validator {
public boolean supports(Class clazz) {
return Customer.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
Customer customer = (Customer)target;
// other constraint checks
errors.pushNestedPath("address");
getAddressValidator(customer.getAddress(), errors);
errors.popNestedPath();
}

private Validator addressValidator = null;
public void setAddressValidator(Validator addressValidator) {
this.addressValidator = addressValidator;
}
private Validator getAddressValidator() {
if (this.addressValidator = null) {
throw new IllegalStateException("Address validator is not available");

280 CHAPTER 9 ■VALIDATION

Free download pdf