Spring MVC 参数依赖注入时,String参数注入为Date类型

在Controller里面增加:

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		// 对于需要转换为Date类型的属性,使用DateEditor进行处理
		binder.registerCustomEditor(Date.class, new SpringBindDateEditor());
	}
public class SpringBindDateEditor extends PropertyEditorSupport {
	Logger logger=Logger.getLogger(SpringBindDateEditor.class);
    private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static void main(String[] args) throws Exception {
    	System.out.println(TIMEFORMAT.parse("2014-10-30 23:50"));;
	}
    private DateFormat dateFormat;
    private boolean allowEmpty = true;

    public SpringBindDateEditor() {
    }

    public SpringBindDateEditor(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    public SpringBindDateEditor(DateFormat dateFormat, boolean allowEmpty) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
    }

    /**
     * Parse the Date from the given text, using the specified DateFormat.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
    	System.out.println(text);
        if (this.allowEmpty && !org.apache.commons.lang3.StringUtils.isNotEmpty(text)) {
            // Treat empty String as null value.
            setValue(null);
        } else {
            try {
                if(this.dateFormat != null)
                    setValue(this.dateFormat.parse(text));
                else {
                    if(text.contains(":")){
                    	System.out.println("格式化!"+text);
                    	Date date=TIMEFORMAT.parse(text);
                    	System.out.println("Passed ");
                        setValue(date);
                        
                    }
                    else
                        setValue(DATEFORMAT.parse(text));
                }
            } catch (ParseException ex) {
            	logger.error("绑定时间出错"+text);
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }

    /**
     * Format the Date as String, using the specified DateFormat.
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        DateFormat dateFormat = this.dateFormat;
        if(dateFormat == null)
            dateFormat = TIMEFORMAT;
        return (value != null ? dateFormat.format(value) : "");
    }
}


你可能感兴趣的:(Spring MVC 参数依赖注入时,String参数注入为Date类型)