一般来说,这个方法是在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); }
}
1处是beanUtils工具包中的一个方法,该方法用来转换类型,ConvertUtils.register函数支持8种基本类型与String自动转换。2.用来将前台jsp页面或者html页面的传过来的参数通过parameterMap封装在map集合中,通过映射,将页面的内容先使用request获得,然后将之转换为Map(通过request.parameterMap()),然后就可以使用BeanUtils.populate(Object bean, Map properties)方法将前台jsp或者html页面的数据属性映射到bean中,也就相当于将数据封装到bean中。随后,我们就可以通过bean.getXxx()方法来获取相应属性的值了。