大家好,又见面了,我是你们的朋友全栈君。
BeanUtils的populate方法之日期处理
BeanUtils.populate(Obj, Map);可以使map转对象,但是如果是Obj有个日期字段而Map中这个字段为空时候就会报错,无法赋值,这个时候就需要一个日期转换器!
首先写一个日期转换器
package com.hzdl.examination.web;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtilsBean;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
public class DateTimeConverter implements Converter {
private static final String DATE = "yyyy-MM-dd";
private static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
private static final String TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SSS";
@Override
public Object convert(Class type, Object value) {
// TODO Auto-generated method stub
return toDate(type, value);
}
public static Object toDate(Class type, Object value) {
if (value == null || "".equals(value))
return null;
if (value instanceof String) {
String dateValue = value.toString().trim();
int length = dateValue.length();
if (type.equals(java.util.Date.class)) {
try {
DateFormat formatter = null;
if (length <= 10) {
formatter = new SimpleDateFormat(DATE, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue);
}
if (length <= 19) {
formatter = new SimpleDateFormat(DATETIME, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue);
}
if (length <= 23) {
formatter = new SimpleDateFormat(TIMESTAMP, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return value;
}
//调用此方法封装bean map为requeset.getParamteMap,object为空对象
public static void transMap2Bean(Map<String, Object> map, Object obj) {
try {
DateTimeConverter dtConverter = new DateTimeConverter();
ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
convertUtilsBean.deregister(Date.class);
convertUtilsBean.register(dtConverter, Date.class);
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean,
new PropertyUtilsBean());
beanUtilsBean.populate(obj, map);
} catch (Exception e) {
}
return;
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/158770.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...