天天看點

開源元件:(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