一般來說,這個方法是在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()方法來獲取相應屬性的值了。
參考鏈接:https://blog.csdn.net/lvhaoguang0/java/article/details/80820960