使用自定义验证器在地图上进行JSR-303验证

时间:2015-01-29 09:01:17

标签: java spring bean-validation thymeleaf

我使用Spring和Thymeleaf填写表单:

<form method="post" th:action="@{/postForm}" th:object="${myForm}"><!--/* model.addAttribute("myForm", new MyForm()) */-->
    <input type="text" th:each="id : ${idList}" th:field="*{map['__${id}__']}" /><!--/* results in map['P12345'] */-->
</form>

MyForm看起来像这样:

public class MyForm {
    @Quantity
    private Map<String, String> map = new HashMap<String, String>();

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }
}

正如您所看到的,我创建了一个自定义注释@Quantity,它应该检查输入值是否可以解析为BigDecimal

@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = QuantityValidator.class)
@Documented
public @interface Quantity {
    String message() default "{com.example.form.validation.constraints.Quantity}";
    Class<? extends Payload>[] payload() default {};
    Class<?>[] groups() default {};
}

public class QuantityValidator implements ConstraintValidator<Quantity, Map<String, String>> {
    private final DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance();
    private final ParsePosition pos = new ParsePosition(0);

    @Override
    public void initialize(Quantity quantity) {
        format.setParseBigDecimal(true);
    }

    @Override
    public boolean isValid(Map<String, String> map, ConstraintValidatorContext context) {
        List<String> invalidFieldsList = new ArrayList<String>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            String quantity = entry.getValue();
            if (quantity != null && !quantity.isEmpty()) {
                if ((BigDecimal) format.parse(quantity, pos) == null) {
                    invalidFieldsList.add(entry.getKey());
                }
            }
        }

        if (!invalidFieldsList.isEmpty()) {
            context.disableDefaultConstraintViolation();

            for (String field : invalidFieldsList) {
                context.buildConstraintViolationWithTemplate("Invalid Quantity for Field: " + field).addNode(field).addConstraintViolation();
            }

            return false;
        }

        return true;
    }
}

现在在我的Controller类中,我这样做:

@Controller
public class MyController {
    @RequestMapping(value = "/postForm", method = RequestMethod.POST)
    public void postForm(@ModelAttribute @Valid MyForm myForm, BindingResult bindingResult) {
        if (!bindingResult.hasErrors()) {
            // do some stuff
        }
    }
}

但是在尝试将NotReadablePropertyException放入文本字​​段时获取d以测试验证:

java.lang.IllegalStateException: JSR-303 validated property 'map.P12345' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)
Caused by:
org.springframework.beans.NotReadablePropertyException: Invalid property 'map.P12345' of bean class [com.example.form.MyForm]: Bean property 'map.P12345' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:726) ~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
    at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:717) ~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
    at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99) ~[spring-context-4.1.1.RELEASE.jar:4.1.1.RELEASE]
    at org.springframework.validation.AbstractBindingResult.getRawFieldValue(AbstractBindingResult.java:283) ~[spring-context-4.1.1.RELEASE.jar:4.1.1.RELEASE]
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:143) ~[spring-context-4.1.1.RELEASE.jar:4.1.1.RELEASE]
    ... 84 more

以下是我阅读的示例,并希望使用自定义验证器进行扩展:http://viralpatel.net/blogs/spring-mvc-hashmap-form-example/

修改: 注释掉@Valid注释并检查myForm.getMap()包含的内容时,地图填充正确:

@Controller
public class MyController {
    private final Logger log = LogManager.getLogger(getClass());

    @RequestMapping(value = "/postForm", method = RequestMethod.POST)
    public void postForm(@ModelAttribute /*@Valid*/ MyForm myForm, BindingResult bindingResult) {
        // Output:
        // P12345: d
        // P67890: 
        for (Map.Entry<String, String> entry : myForm.getMap().entrySet()) {
            log.debug(entry.getKey() + ": " + entry.getValue());
        }
    }
}

1 个答案:

答案 0 :(得分:3)

ConstraintValidatorContext假设您正在构建对象图中实际可导航属性的路径。 Bean Validation实际上并没有验证这一点,所以理论上你可以添加任何东西,但是看起来Spring集成确实使用了这个路径。可能将错误映射到正确的UI元素(我不知道Spring代码)。您要做的是确保为正确的节点添加约束违规。 API实际上允许遍历地图。看起来像:

context.buildConstraintViolationWithTemplate( message )
        .addPropertyNode( "foo" )
        .addPropertyNode( null ).inIterable().atKey( "test" )
        .addConstraintViolation();  

&#39;空&#39;在这种情况下表示映射到键的值。这与将违规添加到值本身的属性(即:

)形成对比
context.buildConstraintViolationWithTemplate( message )
        .addPropertyNode( "foo" )
        .addPropertyNode( "bar" ).inIterable().atKey( "test" )