Validation
Spring提供了一个Validator接口,您可以使用它来验证对象。Validator接口通过使用Errors对象来工作,以便在进行验证时,验证器可以向Errors对象报告验证失败
public class Person {
private String name;
private int age;
// the usual getters and setters...
}
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");
}
}
}
Data Binding
数据绑定对于将用户输入绑定到目标对象非常有用,其中用户输入是一个映射,属性路径作为键,遵循JavaBeans约定。DataBinder是支持此功能的主要类,它提供了两种绑定用户输入的方法:
- Constructor binding
- Property binding with BeanWrapper
Spring Type Conversion
- Converter SPI
package org.springframework.core.convert.converter;
public interface Converter<S, T> {
T convert(S source);
}
Spring Field Formatting
package org.springframework.format;
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
引用:https://www.cnblogs.com/daimzh/p/12854385.html