对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cn

使用 Spring 的 Validator 接口进行验证

Spring 具有一个可用于验证对象的接口。该接口通过使用对象来工作,因此,在验证时, 验证程序可以向对象报告验证失败。ValidatorValidatorErrorsErrorsspring-doc.cn

请考虑以下小型数据对象示例:spring-doc.cn

public class Person {

	private String name;
	private int age;

	// the usual getters and setters...
}
class Person(val name: String, val age: Int)

下一个示例通过实现 接口的两种方式如下:Personorg.springframework.validation.Validatorspring-doc.cn

  • supports(Class):这能否验证提供的实例 ?ValidatorClassspring-doc.cn

  • validate(Object, org.springframework.validation.Errors):验证给定的对象 并且,如果出现验证错误,则将它们注册到给定的对象。Errorsspring-doc.cn

实现 a 相当简单,尤其是当您知道 Spring Framework 也提供的帮助程序类时。以下内容 实例的示例实现:ValidatorValidationUtilsValidatorPersonspring-doc.cn

public class PersonValidator implements Validator {

	/**
	 * This Validator validates only Person instances
	 */
	public boolean supports(Class clazz) {
		return Person.class.equals(clazz);
	}

	public void validate(Object obj, Errors e) {
		ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
		Person p = (Person) obj;
		if (p.getAge() < 0) {
			e.rejectValue("age", "negativevalue");
		} else if (p.getAge() > 110) {
			e.rejectValue("age", "too.darn.old");
		}
	}
}
class PersonValidator : Validator {

	/**
	 * This Validator validates only Person instances
	 */
	override fun supports(clazz: Class<*>): Boolean {
		return Person::class.java == clazz
	}

	override fun validate(obj: Any, e: Errors) {
		ValidationUtils.rejectIfEmpty(e, "name", "name.empty")
		val p = obj as Person
		if (p.age < 0) {
			e.rejectValue("age", "negativevalue")
		} else if (p.age > 110) {
			e.rejectValue("age", "too.darn.old")
		}
	}
}

类上的方法用于 如果是 Reject 属性,则拒绝该属性或空字符串。请查看 ValidationUtils javadoc 以查看除了前面显示的示例之外,它还提供了哪些功能。staticrejectIfEmpty(..)ValidationUtilsnamenullspring-doc.cn

虽然当然可以实现单个类来验证每个 的嵌套对象中,最好将验证 logic 中每个嵌套的 Object 类在其自己的 implementation中。一个简单的 “丰富”对象的示例是由两个属性(第一个和第二个名称)和一个复杂对象组成的 A。 对象 可以独立于对象使用,因此已实现 Distinct。如果您希望重用包含的 logic 在类中,无需使用复制和粘贴,就可以 dependency-inject 或实例化 an 如下例所示:ValidatorValidatorCustomerStringAddressAddressCustomerAddressValidatorCustomerValidatorAddressValidatorAddressValidatorCustomerValidatorspring-doc.cn

public class CustomerValidator implements Validator {

	private final Validator addressValidator;

	public CustomerValidator(Validator addressValidator) {
		if (addressValidator == null) {
			throw new IllegalArgumentException("The supplied [Validator] is " +
				"required and must not be null.");
		}
		if (!addressValidator.supports(Address.class)) {
			throw new IllegalArgumentException("The supplied [Validator] must " +
				"support the validation of [Address] instances.");
		}
		this.addressValidator = addressValidator;
	}

	/**
	 * This Validator validates Customer instances, and any subclasses of Customer too
	 */
	public boolean supports(Class clazz) {
		return Customer.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
		Customer customer = (Customer) target;
		try {
			errors.pushNestedPath("address");
			ValidationUtils.invokeValidator(this.addressValidator, customer.getAddress(), errors);
		} finally {
			errors.popNestedPath();
		}
	}
}
class CustomerValidator(private val addressValidator: Validator) : Validator {

	init {
		if (addressValidator == null) {
			throw IllegalArgumentException("The supplied [Validator] is required and must not be null.")
		}
		if (!addressValidator.supports(Address::class.java)) {
			throw IllegalArgumentException("The supplied [Validator] must support the validation of [Address] instances.")
		}
	}

	/*
	* This Validator validates Customer instances, and any subclasses of Customer too
	*/
	override fun supports(clazz: Class<>): Boolean {
		return Customer::class.java.isAssignableFrom(clazz)
	}

	override fun validate(target: Any, errors: Errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required")
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required")
		val customer = target as Customer
		try {
			errors.pushNestedPath("address")
			ValidationUtils.invokeValidator(this.addressValidator, customer.address, errors)
		} finally {
			errors.popNestedPath()
		}
	}
}

验证错误将报告给传递给验证器的对象。在这种情况下 中,你可以使用 tag 来检查错误消息,但是 您也可以自己检查对象。有关 它提供的方法可以在 Javadoc 中找到。Errors<spring:bind/>Errorsspring-doc.cn