为了账号安全,请及时绑定邮箱和手机立即绑定

Validator 和 DataBinder:如何单独处理多值 bean 字段

Validator 和 DataBinder:如何单独处理多值 bean 字段

慕田峪7331174 2023-09-06 14:59:35
我有一个 bean,其中有一个 List 类型的字段。  public List<MyClass> getter() {    return field;  }  public void setter(MyClass[] source) {    this.field = Arrays.asList(source);  }我已经实现了一个转换器Converter<String, MyClass>,它也可以工作。如果字符串可以转换为 MyClass,则将其转换,如果不能,则抛出异常,并将 的实例FieldError包含在Errors errors = binder.getBindingResult();. 问题是,FieldError#getRejected方法 aString包含有效值和无效值的逗号分隔列表,这可能会产生误导。而且没有空格,这太难看了。像这样:Field has invalid value of "valid,invalid"虽然我更愿意Field has invalid value of "invalid"换句话说,如何让转换和验证对每个值单独进行?
查看完整描述

1 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

虽然spring的做法不是很智能,但是逻辑上是正确的。以下代码可以帮助您找到无效值。


            FieldError fieldError = bindingResult.getFieldError();

            if (fieldError != null && fieldError.contains(TypeMismatchException.class)) {

                TypeMismatchException typeMismatchException = fieldError.unwrap(TypeMismatchException.class);

                ConversionFailedException conversionFailedException = findConversionFailedException(typeMismatchException);

                if (conversionFailedException != null) {

                    Object value = conversionFailedException.getValue();

                    // get the invalid field value

                }

            }

    /**

     * Recursively find the ConversionFailedException

     * @param target

     * @return

     */

    public ConversionFailedException findConversionFailedException(Throwable target) {

        Throwable cause = target.getCause();

        if (cause == null) {

            return null;

        } else if (cause instanceof ConversionFailedException) {

            return (ConversionFailedException)cause;

        }

        return findConversionFailedException(target);

    }


查看完整回答
反对 回复 2023-09-06
  • 1 回答
  • 0 关注
  • 51 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信