今日总结

2020年10月17日:

关于昨日的BeanUtils.populate方法,具体详解如下:

首先,需要导包:org.apache.commons.beanutils.BeanUtils

原理:BeanUtils.populate( Object bean, Map properties )。这个方法会遍历map<key,value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。

部分代码如下:

public static <T> T request2Bean(HttpServletRequest request,Class<T>  beanClass){
try{
T bean = beanClass.newInstance();
//得到request里面所有数据
Map map = request.getParameterMap();
//map{name=aa,password=bb,birthday=1990-09-09}  bean(name=aa,password=dd,birthday=Date)

ConvertUtils.register(new Converter(){


public Object convert(Class type, Object value) {
if(value==null){
return null;
}
String str = (String) value;
if(str.trim().equals("")){
return null;
}

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}, Date.class);
BeanUtils.populate(bean, map);   
return bean;
}catch (Exception e) {
throw new RuntimeException(e);
}

}

此段代码的原理:

这是beanUtils工具包中的一个方法,该方法用来转换类型,ConvertUtils.register函数支持8种基本类型与String自动转换。

用来将前台jsp页面或者html页面的传过来的参数通过parameterMap封装在map集合中,通过映射,将页面的内容先使用request获得,然后将之转换为Map,然后就可以使用BeanUtils.populate(Object bean, Map properties)方法将前台jsp或者html页面的数据属性映射到bean中,也就相当于将数据封装到bean中。随后,我们就可以通过bean.getXxx()方法来获取相应属性的值了。

posted @ 2020-10-17 18:43  一条快乐的小鲸鱼  阅读(37)  评论(0编辑  收藏  举报