【发布时间】: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