【问题标题】:Type mismatch, Spring BindException类型不匹配,Spring BindException
【发布时间】:2015-06-06 22:42:25
【问题描述】:

当我在输入字段中输入诸如“adsf”之类的字母时,spring 会尝试将其绑定到我的“代码”对象的价格(双精度)属性,这会导致绑定异常。如果我想将该字段保留为双精度,我该怎么做才能避免此错误?

POJO

@entity
@Table(name=“CODE”)
public class Code{

    @Column(name=“PRICE”)
    @NotNull
    @DecimalMax(value=“999999999999.999999”)
    @DemimalMin(value=“0.0”)
    private Double price;

    //getters and setters

}

我的控制器

@RequestMapping(value=“validateField”, method=RequestMethod.POST, produces=“application/json”)
public FieldValidatinResult validateField(final Code code, final String field){
    //return statement
}

html页面

<input type=“text” class=“form-control validatable” id=“price”></input>

错误信息:

    Field error in object ‘code’ on field ‘price’: rejected value [adsf]; 
codes[typeMismatch.code.price,typeMismatch.price,typeMismatch.java.lang.Double,typeMismatch]; arguments[org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [code.price,price]; arguments []; default message [price]]; default message 
[Failed to convert property value of type 'java.lang.String' to required type 
'java.lang.Double' for property 'price'; nested exception is 
java.lang.NumberFormatException: For input string: "adsf"]

【问题讨论】:

  • 您必须在客户端进行验证。它不允许插入除数字以外的任何内容。
  • 赶上NumberFormatException ?

标签: java spring validation exception data-binding


【解决方案1】:

我不会说客户端验证是“最好的”,因为它们很容易避免(从表单中获取action url,发布一些垃圾),但它可能是最容易做到的。

我建议在服务器端也添加验证。您已经准备好注释,现在您必须在 Code codeBindingResult 参数上使用 @Validhttp://codetutr.com/2013/05/28/spring-mvc-form-validation/

【讨论】:

    【解决方案2】:

    错误说得很清楚

    [无法将“java.lang.String”类型的属性值转换为所需类型 属性“价格”的“java.lang.Double”;嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“adsf”]

    用户提供了一个非数字输入,当它在服务器上被解析为 double 时,它​​会抛出 NumberFormatException。解决这个问题的最好方法是在客户端处理它。在提交表单之前添加如下验证

    if (!isNaN(parseInt($("#price").val()))) {
        //proceed with form submit
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2020-01-16
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多