在Spring MVC上下文之外使用Spring Validator [英] Using Spring Validator outside of the context of Spring MVC

查看:93
本文介绍了在Spring MVC上下文之外使用Spring Validator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring MVC(@Validate)中使用了带有支持对象和注释的验证器.运作良好.

I've used validators with backing objects and annotations in Spring MVC (@Validate). It worked well.

现在,我正在尝试通过实现自己的Validate来确切了解Spring手册的工作方式.我不确定如何使用"我的验证器.

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.

我的验证者:

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类:

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;
}
}

主要方法:

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?

在旁注中,此形状应该无效,因为它缺少x和y.

On a side note, this shape should be invalid since it lacks an x and a y.

推荐答案

为什么不使用spring提供的org.springframework.validation.MapBindingResult实现?

Why don't you use the implementation that spring offers 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);

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

This will print out all that is in the error messages.

祝你好运

这篇关于在Spring MVC上下文之外使用Spring Validator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆