BeanUtils.populate()空字符串转换日期的解决办法

我们在使用beanutils.populate()封装参数时,如果封装的字符串是空,在转换成date时会出现以上异常,此时可以在工具类中添加静态代码块即可解决:注意导入beanutils 包

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
static {
ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);

ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
return simpleDateFormat.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}, Date.class);
}

猜你喜欢

转载自www.cnblogs.com/xiaoshenke/p/10953281.html
今日推荐