根据操作Spring MVC进行验证的最佳实践

asl*_*lan 11 java validation spring spring-mvc

我正在尝试使用Spring验证执行验证.我想知道执行验证的最佳做法是什么,主要取决于用户的行为,此后,我有三种不同的方法,但我不知道哪种方法最好.

假设,我们有以下类Foo进行验证,并根据用户执行的操作验证许多不同的验证规则.

public class Foo {
    private String name;

    private int age;

    private String description;

    private int evaluation;

    // getters, setters
}
Run Code Online (Sandbox Code Playgroud)

执行这些验证的最佳方法是什么(例如:在创建期间只需要名称和年龄,在评估操作期间,我只需要评估以进行验证等)

解决方案1:每个验证规则一个验证器类

public class CreateFooValidator implements Validator {
    //validation for action create
}
public class EvaluateFooValidator implements Validator {
    //validation for evaluate action
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:一个带有多种方法的验证器类

public class FooValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Foo.class.equals(clazz);
    }

    //the default validate method will be used to validate during create action

    @Override
    public void validate(Object target, Errors errors) {
    //validation required
    }

    //method to validate evaluate action
    public void validateFooEvaluation(Object target, Errors errors) {
    //validation required
    }
    //other validation methods for other actions
}
Run Code Online (Sandbox Code Playgroud)

解决方案3:类Foo中的附加属性操作,一个验证器

public class Foo {

    private String name;

    private int age;

    private String description;

    private int evaluation;

    private String actionOnFoo;

    // getters, setters
}

public class FooValidator implements Validator {

    private final Foo foo = (Foo) target;
    @Override
    public boolean supports(Class<?> clazz) {
        return Foo.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        //test which action is performed by user
        if ("create".equals(foo.getActionOnFoo())) {
            //call for private method that performs validation for create action
        }
    }
    //all private methods
}
Run Code Online (Sandbox Code Playgroud)

3或其他解决方案中最好的解决方案是什么?谢谢!

her*_*man 18

使用JSR-303验证组,这是自Spring MVC 3.1以来也支持的@Validated.

因此,对于每个操作,您应该在控制器中有一个方法.为具有不同规则集的每个可能操作创建验证组,例如

public interface Create {
}

public interface Evaluate {
}
Run Code Online (Sandbox Code Playgroud)

注释Foo与确认的注释包括基团,例如

public class Foo {

    @NotNull(groups = { Create.class, Evaluate.class })
    private String name;

    ...

    @Min(value = 1, message = "Evaluation value needs to be at least 1", groups = { Evaluate.class })
    private int evaluation;

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后注释foo你的控制器方法使用适当的参数@Validated标注,例如@Validated({Evaluate.class})对于evaluate控制器的方法.

你可以在这里找到另一个例子(见第2项):http: //blog.goyello.com/2011/12/16/enhancements-spring-mvc31/

更新:或者,如果由于某种原因您不能/不想使用@Validated,您可以使用注入的Validator实例并将组传递给它的validate方法.这就是它在Spring 3.1之前完成的方式(正如评论文章中的情况).