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

我有一个 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"

换句话说,如何让转换和验证对每个值单独进行?


慕田峪7331174
浏览 68回答 1
1回答

小唯快跑啊

虽然spring的做法不是很智能,但是逻辑上是正确的。以下代码可以帮助您找到无效值。&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FieldError fieldError = bindingResult.getFieldError();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (fieldError != null && fieldError.contains(TypeMismatchException.class)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TypeMismatchException typeMismatchException = fieldError.unwrap(TypeMismatchException.class);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ConversionFailedException conversionFailedException = findConversionFailedException(typeMismatchException);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (conversionFailedException != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object value = conversionFailedException.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // get the invalid field value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Recursively find the ConversionFailedException&nbsp; &nbsp; &nbsp;* @param target&nbsp; &nbsp; &nbsp;* @return&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public ConversionFailedException findConversionFailedException(Throwable target) {&nbsp; &nbsp; &nbsp; &nbsp; Throwable cause = target.getCause();&nbsp; &nbsp; &nbsp; &nbsp; if (cause == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; } else if (cause instanceof ConversionFailedException) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (ConversionFailedException)cause;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return findConversionFailedException(target);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java