commons-beanutils是一个工具类,可以快速封装对象。
1.下载并导入jar包
- 本站下载地址:点击这里(commons-beanutils-1.8.0.jar)
- 其他下载渠道推荐:maven中央仓库
使用maven导入以下坐标
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
2.使用request获取map集合(数据源)
Map<String, String[]> map = req.getParameterMap();
3.创建一个空的User对象(要封装成为的目标对象)
User user = new User();
4.使用populate方法将 map 集合封装为 user 对象
try{
BeanUtils.populate(user,map);
}catch(IllegalAccessException e){
e.printStackTrace();
}catch(InvocationTargetException e){
e.printStackTrace();
}
5.javaBeanUtils的介绍
- 用于封装javaBean,即标准的java类
- 类必须被public修饰
- 必须提供空参的构造器
- 成员变量必须使用private修饰
- 提供公共的setter和getter方法
6.javaBeanUtils的方法介绍
- 封装对象:BeanUtils.populate(class,map);
- 设置属性:BeanUtils.setProperty(class,name,value);
- 获取属性:BeanUtils.getProperty(class,name);
- 成员变量和属性不是同样的概念
- 成员变量,是类中的一个变量
- 属性:是getter和setter截取后的产物(例getUserName)
- 首先截取get和set后面的字段(UserName)
- 然后把该字段首字母变小写(userName)
- 成员变量和属性不是同样的概念
7.注意事项 : 非常重要!!!
这个封装的值, 必须和前端提供了 name 属性的name值是一致的,
在前端封装 name 值时, 必须和实体类中的 属性名一致!!!
如果某些原因无法使前端的 name 属性 和实体类的属性一致, 不要使用此类, 需手写class以完成封装功能!