spring mvc 数据绑定报错 Failed to convert property value of type 'java.lang.String' to required type 'int'

本文详细介绍了如何在Spring MVC中处理空字符串转换为整型时出现的错误,通过自定义IntegerEditor类实现了空字符串默认转换为整型0的功能,避免了异常情况的发生。

刚开始用 spring mvc, 觉得 public String delete( User user ) 这样的控制区获取提交来的参数写法比 struts2 那一堆 setter getter 痛快多了。

不过,刚才发现了提交空字符串到后台自动匹配数值报错,我提交一个空字符串到后台匹配给 int ,然后就报错了。

找到的解决方法,自己定义一个 IntegerEditor,然后在 Controller 里用 initBinder 修改空字符串匹配给 int 的处理方法。


package com.springmvc.controller;

import org.springframework.beans.propertyeditors.PropertiesEditor;

public class IntegerEditor extends PropertiesEditor {
    public void setAsText(String text) throws IllegalArgumentException {
        if( text == null || text.equals("") ){
            text = "0";
        }
        
        setValue( Integer.parseInt(text) );
    }

    public String getAsText() {
        return getValue().toString();
    }
    
}


在控制器里调用它:

    @InitBinder
    protected void initBinder(WebDataBinder binder) {                       
        binder.registerCustomEditor(Integer.class, null, new IntegerEditor() );
        binder.registerCustomEditor(int.class, null, new IntegerEditor() );
    }       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值