Spring mvc 特殊字段的注入

binder.registerCustomEditor 方法的示例:

   在学习BaseCommandController时,我们知道,当提交表单时,controller会把表单元素注入到command类里,但是系统注入的只能是基本类型,如int,char,String。但当我们在command类里需要复杂类型,如Integer,date,或自己定义的类时,controller就不能完成自动注入; 一般的做法是在自己的controller里override initBinder()方法。

  public 

   public class UserController extends SimpleFormController {
       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()方法。希望仔细思考一下registerCustomEditor方法的参数含义。

下面是IntegerEditor()方法:

import java.beans.PropertyEditorSupport;

public class IntegerEditor extends PropertyEditorSupport {

 public String getAsText() {
  Integer value = (Integer) getValue();
  if(null == value){
   value = new Integer(0);
  }
  return value.toString();
 }

 public void setAsText(String text) throws IllegalArgumentException {
  Integer value = null;
  if(null != text && !text.equals("")){
   value = Integer.valueOf(text);
  }
  setValue(value);
 }
}

下面是DateEditor()方法:

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateEditor extends PropertyEditorSupport {

 public String getAsText() {
  Date value = (Date) getValue();
  if(null == value){
   value = new Date();
  }
  SimpleDateFormat df =new SimpleDateFormat("yyyy-MM-dd");
  return df.format(value);
 }

 public void setAsText(String text) throws IllegalArgumentException {
  Date value = null;
  if(null != text && !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方法请求时会调用。

  

原文地址:https://www.cnblogs.com/hm1990hpu/p/7985451.html