Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

validation - Using Spring Validator outside of the context of Spring MVC

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why don't you use the implementation that spring offers org.springframework.validation.MapBindingResult?

You can do:

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.

Good luck


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...