spring mvc表单数据绑定,对于基本类型和日期的处理WebDataBinder

来源:互联网 发布:云计算用什么语言 编辑:程序博客网 时间:2024/06/07 00:30

因为对于原生基本类型的form表单绑定,会出错。需要指定具体的类型编辑器。用法如下:首先在BaseAction中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器。剩下的控制器都继承该类。CustomDateEditor spring自己提供了。

这个是基类BaseAction:

public class BaseAction {@InitBinderprotected void initBinder(WebDataBinder binder) {binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));binder.registerCustomEditor(int.class, new IntegerEditor());binder.registerCustomEditor(long.class, new LongEditor());binder.registerCustomEditor(double.class, new DoubleEditor());binder.registerCustomEditor(float.class, new FloatEditor());}}


下面是各个编辑器类:

Spring提供了CustomNumberEditor,也可以不用些编辑器类。使用构造函数构造相应的编辑器类。

public class DoubleEditor extends PropertiesEditor {@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (text == null || text.equals("")) {text = "0";}setValue(Double.parseDouble(text));}@Overridepublic String getAsText() {return getValue().toString();}}

import org.springframework.beans.propertyeditors.PropertiesEditor;public class IntegerEditor extends PropertiesEditor {@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (text == null || text.equals("")) {text = "0";}setValue(Integer.parseInt(text));}@Overridepublic String getAsText() {return getValue().toString();}}

public class LongEditor extends PropertiesEditor {@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (text == null || text.equals("")) {text = "0";}setValue(Long.parseLong(text));}@Overridepublic String getAsText() {return getValue().toString();}}

public class FloatEditor extends PropertiesEditor {@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (text == null || text.equals("")) {text = "0";}setValue(Float.parseFloat(text));}@Overridepublic String getAsText() {return getValue().toString();}}


原创粉丝点击