天天看点

springMVC属性值绑定(日期类型转…

import java.beans.PropertyEditorSupport; import java.sql.Timestamp; import java.text.SimpleDateFormat; import org.springframework.util.StringUtils; import java.text.ParseException;

public class CustomTimestampEditor extends PropertyEditorSupport { private final SimpleDateFormat dateFormat;     private final boolean allowEmpty;     private final int exactDateLength;       public CustomTimestampEditor(SimpleDateFormat dateFormat, boolean allowEmpty) {         this.dateFormat = dateFormat;         this.allowEmpty = allowEmpty;         this.exactDateLength = -1;     }       public CustomTimestampEditor(SimpleDateFormat dateFormat,             boolean allowEmpty, int exactDateLength) {         this.dateFormat = dateFormat;         this.allowEmpty = allowEmpty;         this.exactDateLength = exactDateLength;     }       public void setAsText(String text) throws IllegalArgumentException {         if ((this.allowEmpty) && (!(StringUtils.hasText(text)))) {             setValue(null);         } else {             if ((text != null) && (this.exactDateLength >= 0)                     && (text.length() != this.exactDateLength)) {                 throw new IllegalArgumentException (                         "Could not parse date: it is not exactly"                                 + this.exactDateLength + "characters long");             }             try {                 setValue(new Timestamp(this.dateFormat.parse(text).getTime()));             } catch (ParseException ex) {                 throw new IllegalArgumentException ("Could not parse date: "                         + ex.getMessage(), ex);             }         }     }       public String getAsText() {         Timestamp value = (Timestamp) getValue();         return ((value != null) ? this.dateFormat.format(value) : "");     }

}

上面为自定义的类就是将前台日期格式转换成timestamp类型。 然后再controller类的最前面加入如下方法: @InitBinder     public void initBinder(WebDataBinder binder) {         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");             dateFormat.setLenient(false);             binder.registerCustomEditor(Timestamp.class, new CustomTimestampEditor(dateFormat, true));     }

解释: binder.registerCustomEditor(Timestamp.class, new CustomTimestampEditor(dateFormat, true)); 这个方法中的new的类可以是自定义的类,也可以使用一些已有的类即已经继承并实现PropertyEditorSupport类的类。 具体默认的类有哪些可以去看PropertyEditorSupport这个类中的源码,因为你自定义的类也是继承的这个类。