我在Spring MVC(@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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要验证的Shape类:
public class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x …Run Code Online (Sandbox Code Playgroud)