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這個類中的源碼,因爲你自定義的類也是繼承的這個類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章