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

刚开始用 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() );
    }       

你可能感兴趣的:(spring,mvc)