当我在输入字段中输入诸如“adsf
”之类的字母时,spring 尝试将其绑定(bind)到“Code”对象的价格( double )属性,这会导致绑定(bind)异常。如果我想将该字段保留为 double ,我该怎么做才能避免此错误?
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
}
我的 Controller
@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"]
最佳答案
我不会说客户端验证是“最好的”,因为它们可以很容易地避免(从表单中获取 action
url,发布一些垃圾),但它可能是最容易做到的。
我建议也在服务器端添加验证。您已准备好注释,现在必须在 Code code
和 BindingResult
参数上使用 @Valid
。 http://codetutr.com/2013/05/28/spring-mvc-form-validation/ <- 这似乎是一些有用的教程。
关于java - 类型不匹配,Spring BindException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405125/