java - 类型不匹配,Spring BindException

标签 java spring validation exception data-binding

当我在输入字段中输入诸如“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 codeBindingResult 参数上使用 @Validhttp://codetutr.com/2013/05/28/spring-mvc-form-validation/ <- 这似乎是一些有用的教程。

关于java - 类型不匹配,Spring BindException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405125/

相关文章:

javascript - 验证文本区域中超长单词的用户输入

java - 从 Optional<Object> 创建对象

java - 如何按内部键降序排序嵌套映射,然后按内部值升序排序?

java - 将 xml 文件中的字符串日期与今天的日期进行比较,如果日期已过期,则从 xml 中删除该节点。字符串日期的格式为 dd/MM/yy

Java StateBased 游戏 - 在 eclipse 外部运行

java - 如何使用spring aop记录@RequestMapping注解的方法的成本时间?

spring - Spring Boot中Jooq DSLContext的使用

java - Guice DI 绑定(bind),无需添加 Guice 注解

python - 确定任何正则表达式的输入类型

ruby-on-rails - 仅在更新时验证