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

package com.rk.entity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DogInfo
{
	private int id;
	private String name;
	private int age;
	private Date birthDay;
	public int getId()
	{
		return id;
	}
	public void setId(int id)
	{
		this.id = id;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	public Date getBirthDay()
	{
		return birthDay;
	}
	public void setBirthDay(Date birthDay)
	{
		this.birthDay = birthDay;
	}
	private String format(Date date)
	{
		if(date == null) return "null";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}
	
	@Override
	public String toString()
	{
		
		return "[Id="+this.id+",Name="+this.name+",Age="+this.age+",BirthDay="+format(this.birthDay)+"]";
	}
}


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的属性名称一致】

package com.rk.demo;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.rk.entity.DogInfo;

public class Demo01
{
	//1. 对javabean的基本操作
	public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
	{
		DogInfo dog = new DogInfo();
		// a. 基本操作
//		dog.setId(1);
//		dog.setName("汪汪");
//		dog.setAge(2);
		
		// b. BeanUtils组件实现对象属性的拷贝
		BeanUtils.copyProperty(dog, "name", "小汪");//Copy the specified property value to the specified destination bean, performing any type conversion that is required.
		BeanUtils.setProperty(dog, "age", 2);//Set the specified property value, performing type conversions as required to conform to the type of the destination property.
		// 总结1: 对于基本数据类型,会自动进行类型转换!
		
		// c. 对象的拷贝
		DogInfo dog2 = new DogInfo();
		BeanUtils.copyProperties(dog2, dog);//Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
		
		// d. map数据,拷贝到对象中
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("name", "小黑");
		map.put("age", 3);
		// 注意:map中的key要与javabean的属性名称一致
		BeanUtils.populate(dog, map);//Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.
		System.out.println(dog);
	}
}


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

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

package com.rk.demo;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import com.rk.entity.DogInfo;

public class Demo02
{
	public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
	{
		String strId = "20";
		String name = "汪旺";
		String birth = "2015-09-19";
		
		// 注册日期类型转换器:1, 自定义的方式
		ConvertUtils.register(new Converter()
		{
			@Override
			// 转换的内部实现方法,需要重写
			public Object convert(Class type, Object value)
			{
				// 判断
				if(type != Date.class)
				{
					return null;
				}
				if(value == null || ("".equals(value.toString().trim())))
				{
					return null;
				}
				try {
					// 字符串转换为日期
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					return sdf.parse(value.toString().trim());
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			}
		}, Date.class);
		
		// 对象
		DogInfo dog = new DogInfo();
		// 把数据封装到对象中
		BeanUtils.copyProperty(dog, "id", strId);
		BeanUtils.copyProperty(dog, "name", name);
		BeanUtils.copyProperty(dog, "birthDay", birth);
		
		System.out.println(dog);
	}
}

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

package com.rk.demo;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import com.rk.entity.DogInfo;

public class Demo03
{
	//2. 使用提供的日期类型转换器工具类
	public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
	{
		String strId = "20";
		String name = "汪旺";
		String birth = "2015-09-19";
		
		// 注册日期类型转换器:2, 使用组件提供的转换器工具类
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		
		// 对象
		DogInfo dog = new DogInfo();
		// 把数据封装到对象中
		BeanUtils.copyProperty(dog, "id", strId);
		BeanUtils.copyProperty(dog, "name", name);
		BeanUtils.copyProperty(dog, "birthDay", birth);
		
		System.out.println(dog);
	}
}


4、应用

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

使用的方法:

Map javax.servlet.ServletRequest.getParameterMap()

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


WebUtil.java

package com.rk.utils;

import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

public class WebUtil
{
	@Deprecated
	public static <T> T copyToBean_old(HttpServletRequest request, Class<T> clazz) {
		try {
			// 创建对象
			T t = clazz.newInstance();
			
			// 获取所有的表单元素的名称
			Enumeration<String> enums = request.getParameterNames();
			// 遍历
			while (enums.hasMoreElements()) {
				// 获取表单元素的名称:<input type="password" name="pwd"/>
				String name = enums.nextElement();  // pwd
				// 获取名称对应的值
				String value = request.getParameter(name);
				// 把指定属性名称对应的值进行拷贝
				BeanUtils.copyProperty(t, name, value);
			}
			
			return t;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 处理请求数据的封装
	 */
	public static <T> T copyToBean(HttpServletRequest request, Class<T> clazz) {
		try {
			// 创建对象
			T t = clazz.newInstance();
			ConvertUtils.register(new DateLocaleConverter(), Date.class);
			// 注册日期类型转换器
			ConvertUtils.register(new DateLocaleConverter(), Date.class);
			//将数据填充到实体对象中
			BeanUtils.populate(t, request.getParameterMap());
			return t;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static <T> T copyToBean(Map map, Class<T> clazz) {
		try {
			// 创建对象
			T t = clazz.newInstance();
			// 注册日期类型转换器
			ConvertUtils.register(new DateLocaleConverter(), Date.class);
			//将数据填充到实体对象中
			BeanUtils.populate(t, map);
			return t;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}


DogServlet.java

package com.rk.servlet;


import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rk.entity.DogInfo;
import com.rk.utils.WebUtil;

public class DogServlet extends HttpServlet
{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Map map = request.getParameterMap();
		DogInfo dog = WebUtil.copyToBean(map, DogInfo.class);
		response.getWriter().println(dog);
	}

}


浏览器访问地址:

http://localhost:8080/myweb/dog?id=1&name=xiaogou&age=8&birthDay=1980-09-08

开源组件:(2)BeanUtils_Utils