I've used validators with backing objects and annotations in Spring MVC (@Validate). It worked well.
Now I'm trying to understand exactly how it works with the Spring manual by implementing my own Validate. I am not sure as to how to "use" my validator.
My Validator:
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");
}
}
}
The Shape class that I seek to validate:
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;
}
}
Main method:
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);
}
}
Since Errors is just an interface, I can't really instantiate it like an ordinary class. How do I actually "use" my validator to confirm that my shape is either valid or invalid?
On a side note, this shape should be invalid since it lacks an x and a y.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…