spring mvc绑定对象String转Date解决入参不能是Date的问题
生活随笔
收集整理的這篇文章主要介紹了
spring mvc绑定对象String转Date解决入参不能是Date的问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用spring的mvc,直接將頁面參數(shù)綁定到對象中,對象中有屬性為Date時會報錯,此時需要處理下。
同樣的,其他的需要處理的類型也可以用這種方法。
在controller中加入代碼
?
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { //對于需要轉(zhuǎn)換為Date類型的屬性,使用DateEditor進行處理 binder.registerCustomEditor(Date.class, new DateEditor(TIMEFORMAT, true)); }?
DateEditor為自定義的處理類,繼承自PropertyEditorSupport,處理方法為public void setAsText(String text) throws IllegalArgumentException
?
package com.elong.activity.web.filter;import java.beans.PropertyEditorSupport; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;import com.elong.common.util.StringUtils;/*** * (入?yún)⑥D(zhuǎn)化)** <p>* 修改歷史: <br> * 修改日期 修改人員 版本 修改內(nèi)容<br> * -------------------------------------------------<br> * 2015年6月15日 下午6:16:17 user 1.0 初始化創(chuàng)建<br>* </p> ** @author Peng.Li * @version 1.0 * @since JDK1.7*/ public class DateEditor extends PropertyEditorSupport {private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");private DateFormat dateFormat;private boolean allowEmpty = true;public DateEditor() {}public DateEditor(DateFormat dateFormat) {this.dateFormat = dateFormat;}public DateEditor(DateFormat dateFormat, boolean allowEmpty) {this.dateFormat = dateFormat;this.allowEmpty = allowEmpty;}/** * Parse the Date from the given text, using the specified DateFormat. */@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (this.allowEmpty && StringUtils.isBlank(text)) {// Treat empty String as null value.setValue(null);} else {try {if (this.dateFormat != null)setValue(this.dateFormat.parse(text));else {if (text.contains(":"))setValue(TIMEFORMAT.parse(text));elsesetValue(DATEFORMAT.parse(text));}} catch (ParseException ex) {throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);}}}/** * Format the Date as String, using the specified DateFormat. */@Overridepublic String getAsText() {Date value = (Date) getValue();DateFormat dateFormat = this.dateFormat;if (dateFormat == null)dateFormat = TIMEFORMAT;return (value != null ? dateFormat.format(value) : "");}}第二種是使注解的方式:
import org.springframework.format.annotation.DateTimeFormat;
/*** 入住日期*/@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date checkInTime;/*** 離店日期*/@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date checkOutTime;詳細說明見博客:http://relive123-yahoo-com-cn.iteye.com/blog/1678376
?
?
?
總結(jié)
以上是生活随笔為你收集整理的spring mvc绑定对象String转Date解决入参不能是Date的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 秋的原野教案一等奖
- 下一篇: 形容战友情深的句子181个