【问题标题】:Using Spring Validator outside of the context of Spring MVC在 Spring MVC 的上下文之外使用 Spring Validator
【发布时间】: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


    【解决方案1】:

    为什么不使用 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);
    

    这将打印出错误消息中的所有内容。

    祝你好运

    【讨论】:

    • 这就像一个魅力!我只是希望文档能够在验证概念首次出现时显示它是如何工作的......
    • 你能告诉我们为什么我们需要第二个参数,Shape.class.getName()吗?
    猜你喜欢
    • 1970-01-01
    • 2015-05-04
    • 2017-07-06
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 2013-05-12
    • 2021-12-21
    • 2017-10-27
    相关资源
    最近更新 更多