总共方法有三种:
第一种:繁重操作解决方式:
在 Controller 里面不写 InitBinder 方法; 直接在请求实体类里面将DATE 类型的字段 注解 @DateTimeFormat("格式")
第二种:比较繁重操作解决方式:
在 Controller 里面写 InitBinder 方法; 里面写多个日期格式;将特殊的标出;如下代码:
@InitBinder
public void initBinder(WebDataBinder b) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
b.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
DateFormat df2 = new SimpleDateFormat("yyyy-MM");
String[] fileds = {"字段名", "字段名", "字段名"};
for(String filed : fileds){
b.registerCustomEditor(Date.class, filed, new CustomDateEditor(df2, true));
}
}
第三种:轻松解决方式:
自己写一个DATE数据绑定类;然后在Controller 里面写 InitBinder 方法里面应用;如下代码
package com.luwen.dai.util;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpecialDateEditor extends PropertyEditorSupport {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
//防止空数据出错
if(StringUtils.isNotBlank(text)){
date = format.parse(text);
}
} catch (ParseException e) {
format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(text);
} catch (ParseException e1) {
format = new SimpleDateFormat("yyyy-MM");
try{
date = format.parse(text);
}catch (Exception e2) {
logger.error("自动绑定日期数据出错", e);
}
}
}
setValue(date);
}
}
然后在initBinder 方法里直接引用
@InitBinder
public void initBinder(WebDataBinder b) {
b.registerCustomEditor(Date.class, new SpecialDateEditor());
}
以上为 三种 SpringMVC 多个 日期格式 数据类型自动绑定解决方法;