刚开始用 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中处理空字符串转换为整型时出现的错误,通过自定义IntegerEditor类实现了空字符串默认转换为整型0的功能,避免了异常情况的发生。
7150

被折叠的 条评论
为什么被折叠?



