我在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 = 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;
}
}
Run Code Online (Sandbox Code Playgroud)
主要方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
由于Errors只是一个接口,我无法像普通类一样实例化它.如何实际"使用"我的验证器以确认我的形状是有效还是无效?
另外,这个形状应该是无效的,因为它没有x和y.
Sin*_*ski 20
你为什么不使用spring提供的实现org.springframework.validation.MapBindingResult?
你可以做:
Map<String, String> map = new HashMap<String, String>();
MapBindingResult errors = new MapBindingResult(map, Shape.class.getName());
ShapeValidator sv = new ShapeValidator();
Shape shape = new Shape();
sv.validate(shape, errors);
System.out.println(errors);
Run Code Online (Sandbox Code Playgroud)
这将打印出错误消息中的所有内容.
祝好运
| 归档时间: |
|
| 查看次数: |
4954 次 |
| 最近记录: |