Spring MVC 与 Hibernate 验证器。如何按组验证属性?

发布于 2024-11-28 02:15:59 字数 1634 浏览 2 评论 0原文

有两个问题:

1.Sping/MVC使用hibernate验证器,自定义验证器如何显示消息? 例如:使用 Hibernate Validator (JSR 303) 进行跨字段验证

@FieldMatch.List({
    @FieldMatch(fieldName="password",verifyName="passwordVerify",message="password confirm valid!", groups={Default.class})
})
@ScriptAssert(lang="javascript",script="_this.name.equals(_this.verifyCode)")
public class LoginForm {...}

如何使用资源属性文件在jsp中显示消息?

NotEmpty.loginForm.name="用户名不能为空!" NotEmpty.loginForm.password="密码不能为空!"

2.我想在 spring mvc 中使用组验证器,就像一个用于登录和注册的用户表单

    @FieldMatch.List({
    @FieldMatch(fieldName="password",verifyName="passwordVerify",message="password confirm valid!", groups={Default.class})
})@ScriptAssert(lang="javascript",script="_this.name.equals(_this.verifyCode)",groups={Default.class,LoginChecks.class,RegisterChecks.class})
public class LoginForm {
    @NotEmpty(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    @Size(min=3,max=10,groups={LoginChecks.class,RegisterChecks.class})
    private String name;

    @NotEmpty(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    @Size(max=16,min=5,groups={LoginChecks.class,RegisterChecks.class})
    private String password;

    private String passwordVerify;

    @Email(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    private String email;

    private String emailVerify;
...
}

控制器参数注释是@valid,任何注释都支持按组进行组验证器吗?

第一篇文章:)

There are two problems:

1.Sping/MVC use hibernate validater, Custom validater how to show message?
like: Cross field validation with Hibernate Validator (JSR 303)

@FieldMatch.List({
    @FieldMatch(fieldName="password",verifyName="passwordVerify",message="password confirm valid!", groups={Default.class})
})
@ScriptAssert(lang="javascript",script="_this.name.equals(_this.verifyCode)")
public class LoginForm {...}

How to show the message in jsp with resource property file?

NotEmpty.loginForm.name="username can not be empty!"
NotEmpty.loginForm.password="password can not be empty!"

2. I want to use group validater with spring mvc, like one userform for login and register

    @FieldMatch.List({
    @FieldMatch(fieldName="password",verifyName="passwordVerify",message="password confirm valid!", groups={Default.class})
})@ScriptAssert(lang="javascript",script="_this.name.equals(_this.verifyCode)",groups={Default.class,LoginChecks.class,RegisterChecks.class})
public class LoginForm {
    @NotEmpty(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    @Size(min=3,max=10,groups={LoginChecks.class,RegisterChecks.class})
    private String name;

    @NotEmpty(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    @Size(max=16,min=5,groups={LoginChecks.class,RegisterChecks.class})
    private String password;

    private String passwordVerify;

    @Email(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    private String email;

    private String emailVerify;
...
}

Controller parameter annotation is @valid, any annotation support group validater by group?

First post :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

随遇而安 2024-12-05 02:15:59

更新:

Spring 3.1 提供了 @Validated 注释,您可以将其用作 @Valid 的直接替代品,并且它接受组。如果您使用的是 Spring 3.0.x 您仍然可以使用此答案中的代码。

原答案:

这绝对是一个问题。由于 @Valid 注释不支持组,因此您必须自己执行验证。这是我们编写的方法,用于执行验证并将错误映射到 BindingResult 中的正确路径。当我们获得接受组的 @Valid 注释时,这将是美好的一天。

 /**
 * Test validity of an object against some number of validation groups, or
 * Default if no groups are specified.
 *
 * @param result Errors object for holding validation errors for use in
 *            Spring form taglib. Any violations encountered will be added
 *            to this errors object.
 * @param o Object to be validated
 * @param classes Validation groups to be used in validation
 * @return true if the object is valid, false otherwise.
 */
private boolean isValid( Errors result, Object o, Class<?>... classes )
{
    if ( classes == null || classes.length == 0 || classes[0] == null )
    {
        classes = new Class<?>[] { Default.class };
    }
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<Object>> violations = validator.validate( o, classes );
    for ( ConstraintViolation<Object> v : violations )
    {
        Path path = v.getPropertyPath();
        String propertyName = "";
        if ( path != null )
        {
            for ( Node n : path )
            {
                propertyName += n.getName() + ".";
            }
            propertyName = propertyName.substring( 0, propertyName.length()-1 );
        }
        String constraintName = v.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
        if ( propertyName == null || "".equals(  propertyName  ))
        {
            result.reject( constraintName, v.getMessage());
        }
        else
        {
            result.rejectValue( propertyName, constraintName, v.getMessage() );
        }
    }
    return violations.size() == 0;
}

我从我的博客文章中复制了有关我们解决方案的来源。
http://digitaljoel. nerd-herders.com/2010/12/28/spring-mvc-and-jsr-303-validation-groups/

Update:

Spring 3.1 provides the @Validated annotation which you can use as a drop-in replacement for @Valid, and it accepts groups. If you are using Spring 3.0.x You can still use the code in this answer.

Original Answer:

This is definitely a problem. Since the @Valid annotation doesn't support groups, you'll have to perform the validation yourself. Here is the method we wrote to perform the validation and map the errors to the correct path in the BindingResult. It'll be a good day when we get an @Valid annotation that accepts groups.

 /**
 * Test validity of an object against some number of validation groups, or
 * Default if no groups are specified.
 *
 * @param result Errors object for holding validation errors for use in
 *            Spring form taglib. Any violations encountered will be added
 *            to this errors object.
 * @param o Object to be validated
 * @param classes Validation groups to be used in validation
 * @return true if the object is valid, false otherwise.
 */
private boolean isValid( Errors result, Object o, Class<?>... classes )
{
    if ( classes == null || classes.length == 0 || classes[0] == null )
    {
        classes = new Class<?>[] { Default.class };
    }
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<Object>> violations = validator.validate( o, classes );
    for ( ConstraintViolation<Object> v : violations )
    {
        Path path = v.getPropertyPath();
        String propertyName = "";
        if ( path != null )
        {
            for ( Node n : path )
            {
                propertyName += n.getName() + ".";
            }
            propertyName = propertyName.substring( 0, propertyName.length()-1 );
        }
        String constraintName = v.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
        if ( propertyName == null || "".equals(  propertyName  ))
        {
            result.reject( constraintName, v.getMessage());
        }
        else
        {
            result.rejectValue( propertyName, constraintName, v.getMessage() );
        }
    }
    return violations.size() == 0;
}

I copied this source from my blog entry regarding our solution.
http://digitaljoel.nerd-herders.com/2010/12/28/spring-mvc-and-jsr-303-validation-groups/

你不是我要的菜∠ 2024-12-05 02:15:59

至于 @Valid 注释中的验证组支持 - 有一种方法可以做到这一点,我最近发现,它正在重新定义已验证 bean 的默认组:

@GroupSequence({TestForm.class, FirstGroup.class, SecondGroup.class})
class TestForm {

    @NotEmpty
    public String firstField;

    @NotEmpty(groups=FirstGroup.class)
    public String secondField; //not validated when firstField validation fails

    @NotEmpty(groups=SecondGroup.class)
    public String thirdField; //not validated when secondField validation fails
}

现在,您仍然可以使用 @有效,但保留验证组的顺序。

As for validation groups support inside @Valid annotation - there is a way to do it, that I've recently found, it's redefining default group for validated bean:

@GroupSequence({TestForm.class, FirstGroup.class, SecondGroup.class})
class TestForm {

    @NotEmpty
    public String firstField;

    @NotEmpty(groups=FirstGroup.class)
    public String secondField; //not validated when firstField validation fails

    @NotEmpty(groups=SecondGroup.class)
    public String thirdField; //not validated when secondField validation fails
}

Now, you can still use @Valid, yet preserving order with validation groups.

谜泪 2024-12-05 02:15:59

从 Spring 3.1 开始,您可以使用 Spring 的 @Validated 实现基于组的验证,如下所示:

@RequestMapping
public String doLogin(@Validated({LoginChecks.class}) LoginForm) {
    // ...
}

@Validated@Validated 的替代品。

As of Spring 3.1 onwards, you can achieve group based validation by using Spring's @Validated as follows:

@RequestMapping
public String doLogin(@Validated({LoginChecks.class}) LoginForm) {
    // ...
}

@Validated is a substitute for @Valid.

溺孤伤于心 2024-12-05 02:15:59

控制器参数注解是@valid,有注解支持按组分组验证吗?

现在可以使用 @ConvertGroup 注释。看看这个 http://docs .jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-group-conversion

Controller parameter annotation is @valid, any annotation support group validater by group?

It is possible now with @ConvertGroup annotation. Check this out http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-group-conversion

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文