获取bean验证失败的字段名称

时间:2015-11-16 09:08:46

标签: java bean-validation

因此,我正在进行JSR-303 bean验证的类有两个字段,每个字段都应用了相同的模式约束:

@Column(name="test_suite_revision")
@XmlElement(name="test_suite_revision")
@NotNull
@Pattern(regexp = "\\d\\d-\\d\\d-\\d\\d\\d\\d", message = "value must be of the form xx-xx-xxxx")
private String revisionTestSuite;

@Column(name="test_revision")
@XmlElement(name="test_revision")
@NotNull
@Pattern(regexp = "\\d\\d-\\d\\d-\\d\\d\\d\\d", message = "value must be of the form xx-xx-xxxx")
private String revisionTest;

重要 - 此类不是经典Spring MVC webapp中的表单支持类,而是位于Web服务基础的实体类。因此,验证在服务中发生。

现在,使用Web服务的Web客户端是一个Spring MVC,并且有一个表单支持bean,它与一个带有错误消息的地方的jsp绑定。

因此假设用户将格式不正确的字符串输入到两个字段之一中。我可以使用这个非常标准的代码片段来捕获它

    Set<ConstraintViolation<TestCase>> violations = validator.validate( permit);
    if( !violations.isEmpty()) {
        logger.debug( "basic validation FAILED with " + violations.size() + " errors");
        Iterator<ConstraintViolation<TestCase>> iter = violations.iterator();
        while( iter.hasNext()) {
            ConstraintViolation<TestCase> cv = iter.next();
            logger.debug( "invalidValue:" + cv.getInvalidValue());
            logger.debug( "message:" + cv.getMessage());
            ConstraintDescriptor<?> cd = cv.getConstraintDescriptor();
            Map<String, Object> mapp = cd.getAttributes();
            for( String keey : mapp.keySet()) {
                logger.debug("mapp key:" + keey + ":" + mapp.get(keey));
            }
写出来的

basic validation FAILED with 1 errors
invalidValue:050607
message:value must be of the form xx-xx-xxxx
mapp key:message:value must be of the form xx-xx-xxxx
mapp key:payload:[Ljava.lang.Class;@1367702
mapp key:flags:[Ljavax.validation.constraints.Pattern$Flag;@bf5210
mapp key:groups:[Ljava.lang.Class;@a49be5
mapp key:regexp:\d\d-\d\d-\d\d\d\d

这里有一个问题:如何确定WHICH字段验证失败?我似乎找不到提取字段名称的方法,&#34; revisionTest&#34;或&#34; revisionTestSuite&#34; 来自ConstraintViolation对象和ConstraintDescritpor对象。

版本1.1.0中新增的getValidationAppliesTo()方法.javax.validation-api的最终版似乎很有希望,但到目前为止,此方法在运行时抛出了一个AbstractMethodError。啊。

TIA,

仍在学习史蒂夫

1 个答案:

答案 0 :(得分:1)

请参阅ConstraintViolation#getPropertyPath方法:

/**
 * @return the property path to the value from {@code rootBean}
 */
Path getPropertyPath();

Path.Node#getName将为您提供属性名称。对于嵌套bean中的字段名称,您已经走了路径。