【发布时间】:2012-03-07 19:04:09
【问题描述】:
我在 Spring MVC (@Validate) 中使用了带有支持对象和注释的验证器。它运作良好。
现在我试图通过实现我自己的 Validate 来准确了解它是如何与 Spring 手册一起工作的。我不确定如何“使用”我的验证器。
我的验证者:
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.myartifact.geometry.Shape;
public class ShapeValidator implements Validator {
@SuppressWarnings("rawtypes")
public boolean supports(Class clazz) {
return Shape.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "x", "x.empty");
ValidationUtils.rejectIfEmpty(errors, "y", "y.empty");
Shape shape = (Shape) target;
if (shape.getX() < 0) {
errors.rejectValue("x", "negativevalue");
} else if (shape.getY() < 0) {
errors.rejectValue("y", "negativevalue");
}
}
}
我要验证的 Shape 类:
public class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public Shape() {}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
主要方法:
public class ShapeTest {
public static void main(String[] args) {
ShapeValidator sv = new ShapeValidator();
Shape shape = new Shape();
//How do I create an errors object?
sv.validate(shape, errors);
}
}
由于 Errors 只是一个接口,我不能像普通类一样实例化它。我如何实际“使用”我的验证器来确认我的形状是有效还是无效?
顺便说一句,这个形状应该是无效的,因为它缺少 x 和 y。
【问题讨论】:
标签: spring validation