我正在使用spring 3.0创建一个演示应用程序。我必须在屏幕上应用验证,我在网上搜索,发现主要有两种类型的验证与应用程序一起使用:-
希望有人能给我一个在应用程序中实现的好建议。
发布于 2011-12-22 07:53:02
我使用了这两者-我更喜欢Hibernate验证-相当容易实现和相当标准。当您在类路径上有一个实现时,就会自动启用它。下面是一个示例:
@EmailValidator
@NotBlank
@Length(max=65)
private String email;
消息错误字符串从何而来?在WEB中,必须有一个名为messages.properties的文件:
NotBlank.ForgotPasswordBackingObject.email=Email address must be present
有一个标准的@Email注释,但是像me@mycompany这样的电子邮件被认为是有效的,这就是为什么我必须创建自己的@EmailValidator(在标准实现中将regex标志从*更改为+)。我遇到了一些问题:验证的顺序--您希望首先进行的验证,这是通过验证组完成的,但是使用@Valid注释是不可能的,例如:
@RequestMapping(method=RequestMethod.POST, value="/auth/changePassword")
public ModelAndView submitChangePasswordPage(@Valid @ModelAttribute("ChangePasswordBackingObject") ChangePasswordBackingObject backingObject, BindingResult result, Principal principal)
这就是为什么如果您有这种形式的Controller (例如Spring ),那么您必须以某种方式模拟您的逻辑--我也这样做过。
另一件很酷的事情是,您可以同时对两个或多个字段进行验证(我发现这非常有用):
@FieldMatch.List({
@FieldMatch(firstValue = "password" , secondValue = "confirmPassword")
})
public class RequestAccountBackingObject implements Serializable {
private String password;
private String confirmPassword;
以及执行情况:
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchImpl.class)
@Documented
public @interface FieldMatch{
String message() default "{com.errorMessage}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String firstValue();
String secondValue();
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List
{ FieldMatch[] value(); }
}
另一个FieldMatchImpl是:
public class FieldMatchImpl implements ConstraintValidator<FieldMatch, Object>{
private String firstFieldName;
private String secondFieldName;
您需要实现两个方法:
public void initialize(final FieldMatch constraintAnnotation){
firstFieldName = constraintAnnotation.firstValue();
secondFieldName = constraintAnnotation.secondValue();
另外:
public boolean isValid(final Object value, final ConstraintValidatorContext context){
final String firstObj = BeanUtils.getProperty(value, firstFieldName);
final String secondObj = BeanUtils.getProperty(value, secondFieldName);
使用org.apache.commons.beanutils.BeanUtils,您现在可以验证这两个字段。
如下所示:
boolean result = firstObj.equals(secondObj);
if(!result) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(errorMessage).addNode(firstFieldName).addConstraintViolation();
}
另外,到目前为止,使用Hibernate验证是一种乐趣。
https://stackoverflow.com/questions/8600707
复制相似问题