springmvc的bind问题(二)自定义对象有原生类型

本文解决了SpringMVC中因空字符串导致的类型转换错误问题,通过自定义编辑器将空字符串转换为默认数值,确保了应用程序的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springmvc的bind问题(二)自定义对象有原生类型

由于我们的MaterialCategory里面有int agingTime等成员,当页面传入参数为“”时,会报如下错误:
Field error in object 'materialCategory' on field 'agingTime': rejected value []; codes [typeMismatch.materialCategory.agingTime,typeMismatch.agingTime,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [materialCategory.agingTime,agingTime]; arguments []; default message [agingTime]]; default message [Failed to convert property value of type [java.lang.String] to required type [int] for property 'agingTime'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [int] for property 'agingTime': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value]

主要的错误是returned inappropriate value,就是说org.springframework.beans.propertyeditors.CustomNumberEditor类返回了一个不合适的值,查看我们用到的spring2.5.6上的代码

看到代码行里面setAsText这个方法中
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(null);
}else if (this.numberFormat != null) {
// Use given NumberFormat for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
}else {
// Use default valueOf methods for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass));
}
}
当输入的值为“”,也就是StringUtils.hasText返回为false时,设置的是一个null到int中。。。
汗,这当然是不合适的值了噻。不晓得是不是该这么处理,我写了一个类
CustomNativeEditor.java
代码完全拷贝自CustomNumberEditor类,只是修改了其中的这里:
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(0);
} else if (this.numberFormat != null) {
// Use given NumberFormat for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass,
this.numberFormat));
} else {
// Use default valueOf methods for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass));
}
}
修改initbind里面的方法
binder.registerCustomEditor(int.class, null, new CustomNativeEditor(
Integer.class, null , true));
binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(
Long.class, null, true));
binder.registerCustomEditor(long.class, null, new CustomNativeEditor(
Long.class, null, true));
一切搞定。如果要处理输入的是“adsfasdf”等错误字符也不出错的话,就在setAsText里面再做些修改就行了。
不晓得别人遇到这个问题有没有比较简单的办法,我是这样解决的。记录一下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值