项目场景:
使用BeanUtils将map中的所有的参数赋值给JavaBean,但是map中第一类型是String,而JavaBean的类型为Date
所以需要将BeanUtils的string转date
问题描述:
Map接收的数据中全部是String类型的,而User类中的日期是Date类型,类型不同,不能直接使用BeanUtils将map中的所有的参数赋值给JavaBean
Map<String,String[]> map=request.getParameterMap();
User user=new User();
System.out.println(map);
try {
//参数一JavaBean 参数二map
BeanUtils.populate(user,map); //将map中的所有的参数赋值给JavaBean
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
解决方案:
在类中添加一个静态方法 static {
//静态代码块,在加载的时候自动执行,而且只执行一次
//将string转date的转换器注册给beanUtils
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}, Date.class);
}