需求
当后台接收参数类型为Date时,前端传过来的参数类型为String:“2020-05-08 17:08:10”,这样就会出现参数类型不匹配的问题,这种情况下我们就要对接收Date类型参数进行统一处理。Java中提供了PropertyEditorSupport来进行类型转换,我们只需要继承这个类,并且重写它主要的方法就行了。
PropertyEditorSupport
PropertyEditorSupport中通过setAsText(String text)方法来实现转换逻辑,然后调用setValue(Object value)方法将转换后的数据进行保存。
public void setAsText(String text) throws java.lang.IllegalArgumentException {
if (value instanceof String) {
setValue(text);
return;
}
throw new java.lang.IllegalArgumentException(text);
}
自定义DateEditor
继承PropertyEditorSupport并且重写setAsText(String text) 和getAsText()方法。
/**
* Editor - 日期
*/
public class DateEditor extends PropertyEditorSupport {
/**
* 默认的日期格式
*/
private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 能够进行转换的日期格式
*/
public static final String[] DATE_PATTERNS = new String[] { "yyyy", "yyyy-MM", "yyyyMM", "yyyy/MM", "yyyy-MM-dd", "yyyyMMdd", "yyyy/MM/dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", "yyyy/MM/dd HH:mm:ss" };
/**
* 是否将空转换为null
*/
private boolean emptyAsNull;
/**
* 日期格式
*/
private String dateFormat = DEFAULT_DATE_FORMAT;
public DateEditor(boolean emptyAsNull) {
this.emptyAsNull = emptyAsNull;
}
public DateEditor(boolean emptyAsNull, String dateFormat) {
this.emptyAsNull = emptyAsNull;
this.dateFormat = dateFormat;
}
/**
* 获取日期
*/
@Override
public String getAsText() {
Date value = (Date) getValue();
return value != null ? DateFormatUtils.format(value, dateFormat) : StringUtils.EMPTY;
}
/**
* 设置日期
*/
@Override
public void setAsText(String text) {
if (text != null) {
String value = text.trim();
if (emptyAsNull && StringUtils.isEmpty(text)) {
setValue(null);
} else {
try {
setValue(DateUtils.parseDate(value, DATE_PATTERNS));
} catch (ParseException e) {
setValue(null);
}
}
} else {
setValue(null);
}
}
}
通过@InitBinder进行数据绑定
/**
* Controller增强
*/
@ControllerAdvice("xx.xx.controller")
public class BaseControllerAdvice {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateEditor(true));
}
}