spring mvc绑定对象String转Date解决入参不能是Date的问题

时间:2023-03-09 17:01:38
spring mvc绑定对象String转Date解决入参不能是Date的问题

使用spring的mvc,直接将页面参数绑定到对象中,对象中有属性为Date时会报错,此时需要处理下。

同样的,其他的需要处理的类型也可以用这种方法。

在controller中加入代码

 @InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
//对于需要转换为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; /**
*
* (入参转化)
*
* <p>
* 修改历史: <br>
* 修改日期 修改人员 版本 修改内容<br>
* -------------------------------------------------<br>
* 2015年6月15日 下午6:16:17 user 1.0 初始化创建<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.
*/
@Override
public 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));
else
setValue(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.
*/
@Override
public 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