【问题标题】:Spring-MVC bean Validation Type mismtach errorSpring-MVC bean验证类型不匹配错误
【发布时间】:2012-12-13 18:22:04
【问题描述】:

我正在尝试使用 Spring JSR303 验证来验证对象,我有一个表单对象,其中包含一些嵌套对象以及一些表单属性,这是我的表单签名

public class PaymentDetailsForm
{
  private AddressForm billingAddress;
  // other properties and getter and setters

}

在我的AddressForm bean 中,我使用了 Bean 验证注解来验证数据,但我没有在我的 PaymentDetailsForm 中为 billingAddress 使用任何 @Valid 注解。 这是我的 Controller 方法的签名

public String createUpdatePaymentInfos(final Model model,
@ModelAttribute("paymentInfo") @Valid final PaymentDetailsForm form, final BindingResult bindingResult)
{
}

如果我从表单发送正确的数据,一切正常,但如果我省略了 billingAddress 中标记为必需或不为空的任何字段,我将收到以下绑定错误异常

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'paymentInfo' on field 'billingAddress': 
rejected value [com.xxx.storefront.forms.AddressForm@e39f6f1,true]; 
codes [typeMismatch.paymentInfo.billingAddress,typeMismatch.billingAddress,typeMismatch.com.xxx.storefront.forms.AddressForm,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [paymentInfo.billingAddress,billingAddress]; arguments []; default message [billingAddress]]; 
default message [Failed to convert property value of type 'java.lang.String[]' 
to required type 'com.xxx.storefront.forms.AddressForm' for property 'billingAddress';
nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.String[]] to required type [com.xxx.storefront.forms.AddressForm] for property 'billingAddress': 
no matching editors or conversion strategy found]

我期待由于我没有为 billingAddress 属性使用 @valid 注释,因此不应该对其进行验证,但即使它得到验证,我也无法理解上述异常/错误

【问题讨论】:

    标签: spring spring-mvc bean-validation


    【解决方案1】:

    您看到的 bindingResult 看起来不是因为验证错误,可能是因为绑定错误 - 无法将 UI 字段绑定到内部 billingAddress 字段。即使是绑定错误最终也会显示在紧随其后的 bindingresult 参数中,就像您看到的那样。

    【讨论】:

    • 我同意你的输入,我只是在调试这个。这可能是什么原因,因为如果我完全发送所有数据,只有在缺少某些必需数据的情况下,字段才会正确映射,这个问题即将到来
    【解决方案2】:

    这是由于 UI 的一些错误映射,在我的 JSP 页面中,我将地址字段映射到 billingAddress 对象,但有一个隐藏字段,例如

    <form:hidden path="billingAddress" id="billingAddress"/> 
    

    这是错误的原因,因为它试图发送字符串数组,而 Spring 绑定无法区分我正在尝试做什么

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 2020-01-16
      • 2021-04-28
      相关资源
      最近更新 更多