SpringMVC学习笔记----带有复杂类型的command类

来源:互联网 发布:买低价机票软件 编辑:程序博客网 时间:2024/05/23 16:53
在学习BaseCommandController时,我们知道,当提交表单时,controller会把表单元素注入到command类里,但是系统注入的只能是基本类型,如int,char,String。但当我们在command类里需要复杂类型,
如Integer,date,或自己定义的类时,controller就不会那么聪明了。
一般的做法是在自己的controller里override initBinder()方法。这里我们修改一下学习SimpleFormController的那个例子。
覆盖initBinder()方法
在执行请求参数到Command对象绑定之前,初始化一个可用的DataBinder实例,就是有了一个ServletRequestDataBinder之后,我们可以添加自定义的PropertyEdtior

以支持某些特殊数据类型的数据的绑定,或者排除某些不想绑定的请求参数,这些定制行为可以通过覆写initBinder()方法引入


下面的例子是在之前的SimpleFormController基础上进行了一些小小的变动
Command类中的主要变动时增加了一个Date类型的birthday字段,get字段的类型由int变成了Integer,这些都是不能直接将请求参数绑定到Command对象上

public class UserModel {private String account;private String phone;private String city;private Date createTime;private Date birthday;//将int改为Integer private Integer age;

在Controller里面覆盖initBinder()方法。

         /** * 覆盖initBinder()方法 * 在执行请求参数到Command对象绑定之前,初始化一个可用的DataBinder实例,就是有了一个ServletRequestDataBinder之后,我们可以添加自定义的Property         Edtior * 以支持某些特殊数据类型的数据的绑定,或者排除某些不想绑定的请求参数,这些定制行为可以通过覆写initBinder()方法引入 * void registerCustomEditor(Class<?> requiredType,String propertyPath,PropertyEditor propertyEditor) * requiredType - the type of the property.  * propertyPath - the path of the property (name or nested path), or null if registering an editor for all properties of the given type * propertyEditor - editor to register */protected void initBinder(HttpServletRequest req,ServletRequestDataBinder binder)throws Exception{binder.registerCustomEditor(Integer.class, "age", new IntegerEditor());binder.registerCustomEditor(Date.class,"birthday",new DateEditor());}

可以看出使用了binder.registerCustomEditor方法,它是用来注册的。所谓注册即告诉Spring,注册的属性由我来注入,不用你管了。可以看出我们注册了“age”和“birthday”属性。
那么这两个属性就由我们自己注入了。那么怎么注入呢,就是使用IntegerEditor()和DateEditor()方法。

下面是IntegerEditor()方法:

public class IntegerEditor extends PropertyEditorSupport{@Overridepublic String getAsText() {Integer value=(Integer)getValue();if(value==null){value=new Integer(0);}return value.toString();}@Overridepublic void setAsText(String text) throws IllegalArgumentException {Integer value=null;if(text!=null&&!text.equals("")){value=Integer.valueOf(text);}setValue(value);}}
下面是DateEditor()方法:

public class DateEditor extends PropertyEditorSupport{@Overridepublic String getAsText() {Date value=(Date) getValue();if(value==null){value=new Date();}SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");return df.format(value);}@Overridepublic void setAsText(String text) throws IllegalArgumentException {Date value=null;if(text!=null&&!text.equals("")){SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");try{value=df.parse(text);}catch(Exception e){e.printStackTrace();}}setValue(value);}}

getAsText和setAsText是要从新定义的。其中getAsText方法在get方法请求时会调用,而setAsText方法在post方法请求时会调用。

至此复杂Command的绑定原理了解了。

0 0