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) : "");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值