我正在尝试使用 Spring 验证来执行验证。我想知道执行主要取决于用户操作的验证的最佳做法是什么,此后,我有三种不同的方法,但我不知道哪种方法最好。
假设,我们有以下类 Foo 进行验证,并且根据用户执行的操作有许多不同的验证规则。
public class Foo {
private String name;
private int age;
private String description;
private int evaluation;
// getters, setters
}
执行这些验证的最佳方式是什么(例如:在创建过程中只需要姓名和年龄,在评估操作期间,我只需要验证评估等等)
解决方案 1:每个验证规则一个 validator 类
public class CreateFooValidator implements Validator {
//validation for action create
}
public class EvaluateFooValidator implements Validator {
//validation for evaluate action
}
解决方案 2:一个具有多种方法的 validator 类
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
}
解决方案 3:Foo 类中的附加属性操作,一个 validator
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
}
这 3 个或其他解决方案中最好的解决方案是什么? 谢谢!
最佳答案
使用 JSR-303 验证组,从 Spring MVC 3.1 开始,@Validated
也支持。
因此,对于每个操作,您的 Controller 中都应该有一个方法。 为具有不同规则集的每个可能操作创建一个验证组,例如
public interface Create {
}
public interface Evaluate {
}
使用包含组的验证注释来注释 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;
...
}
然后使用适当的 @Validated
注释来注释 Controller 方法的 foo
参数,例如@Validated({Evaluate.class})
用于 evaluate
Controller 方法。
您可以在此处找到另一个示例(参见第 2 项): http://blog.goyello.com/2011/12/16/enhancements-spring-mvc31/
更新:
或者,如果由于某种原因您不能/不想使用 @Validated
,您可以使用注入(inject)的 Validator
实例并将组传递给它的 验证
方法。这就是 Spring 3.1 之前的做法(就像您评论中的文章中的情况一样)。
关于java - 基于 Action 的验证最佳实践 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19089649/