request.getParameterMap()和BeanUtils.populate()的用法笔记
##request.getParameterMap()和BeanUtils.populate()的用法笔记
方法理解:
1、request.getParameterMap()返回的是一个Map(String ,String[])类型,其中String相当于Map的key,String[]相当于value;而且该方法只允许读,不能修改。
2、BeanUtils.populate()的使用需要先引入commons-logging-1.2.jar和commons-beanutils-1.9.4.jar。如果运行报Java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap错误,可继续导入commons-collections-3.2.2.jar;该方法的目的是将Map集合的数据一一对应封装到JavaBean对象的属性中。
jar包下载链接
request.getParameterMap()和BeanUtils.populate()结合使用:
User user = new User();
Map<String, String[]> parameterMap = request.getParameterMap();
try {
//分别将属性设置到对象中
// BeanUtils.setProperty(user,name,name);
//将属性的Map集合封装到对象的属性中
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
request.getParameterMap()方法从前端获取响应的表单数据存储在Map集合中,如前端发送如下数据:
post("/user",{"name":"xiaoming","password":"123456"});
然后可以调用BeanUtils.populate(Bean,Map)将集合数据封装到JavaBean对象的属性中。
注意:你的JavaBean对象属性名必须和前端设置的一致;如:
private String u_name;
private String u_password;
<li><label for="user" class="input-tips2">用户名:</label>
<div class="inputOuter2">
<input type="text" id="user" name="u_name" maxlength="16"
class="inputstyle2"/>
</div>
</li>
<li><label for="passwd" class="input-tips2">密码:</label>
<div class="inputOuter2">
<input type="password" id="passwd" name="u_password" maxlength="16"
class="inputstyle2"/>
JavaBean的u_name、u_password和前端设置需一致,否则无法获取数据。
方法优点:两个方法的结合使用可减少数据获取步骤和冗余代码,使代码块更加简洁。
附加:小编是编程小白,学艺十分不精,如果有错误之处,希望大家指正。