2012-03-07 72 views
8

我在Spring MVC(@Validate)中使用了支持對象和註解的驗證器。它運作良好。在Spring MVC上下文之外使用Spring Validator

現在我試圖通過實現我自己的驗證來了解它如何與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"); 
    } 
} 
} 

形狀類,我試圖驗證:

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

由於錯誤只是一個接口,我可以」實際上它就像普通的類一樣實例化它。我如何真正「使用」驗證器來確認我的形狀是有效還是無效?

請注意,此形狀應該無效,因爲它缺少x和y。

回答

19

爲什麼不使用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); 

這將打印出所有的在錯誤消息。

祝你好運

+3

這工作就像一個魅力!我只希望當驗證的概念第一次出現時,文檔將顯示它是如何工作的... – Harry 2012-03-08 16:16:31

+4

您能否告訴我們爲什麼需要第二個參數Shape.class.getName()? – 2015-01-12 04:56:58