天天看点

开源组件:(2)BeanUtils

1、简介

程序中对javabean的操作很频繁,所以apache提供了一套开源的api,方便对javabean的操作!即BeanUtils组件。

BeanUtils组件,作用是简化javabean的操作!

http://commons.apache.org/proper/commons-beanutils/

http://commons.apache.org/proper/commons-logging/download_logging.cgi

使用BenUtils组件:

1. 引入commons-beanutils-1.9.2.jar核心包

2. 引入日志支持包: commons-logging-1.1.1.jar

3. 引入集合支持包: commons-collections-3.2.1.jar

可以在http://mvnrepository.com/查询各jar包版本的兼容性

如果缺少日志jar文件,报错:

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

如果缺少集合jar文件,报错:

java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap

org.apache.commons.beanutils.BeanUtils

(1)将JavaBean的properties进行赋值,本质上是通过反射

Utility methods for populating JavaBeans properties via reflection.

org.apache.commons.beanutils.ConvertUtils

(1)将String scalar values转换成objects of the specified Class

Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.

public static void register(Converter converter, Class<?> clazz) 

Register a custom Converter for the specified destination Class, replacing any previously registered Converter.

org.apache.commons.beanutils.Converter

(1)类型转换的接口。

General purpose data type converter. It can be registered and used within the BeanUtils package to manage the conversion of objects from one type to another.

准备工作:DogInfo.java

2、实例:基本用法

方法1: 对象属性的拷贝

BeanUtils.copyProperty(dog, "name", "小汪");

BeanUtils.setProperty(dog, "age", 2);

方法2: 对象的拷贝

BeanUtils.copyProperties(dest, origin);

方法3: map数据拷贝到javabean中

BeanUtils.populate(bean, map);【注意:map中的key要与javabean的属性名称一致】

3、实例:日期类型的拷贝

1.自定义日期类型转换器

2.(推荐)使用提供的日期类型转换器工具类

4、应用

在使用Servlet接受浏览器参数的时候,可以使用BeanUtils组件,可以将浏览器传来的参数直接转换成JavaBean对象

使用的方法:

Map javax.servlet.ServletRequest.getParameterMap()

void org.apache.commons.beanutils.BeanUtils.populate(Object bean, Mapproperties),>

WebUtil.java

DogServlet.java

浏览器访问地址:

开源组件:(2)BeanUtils