使用BeanUtils工具封装javaBean

// 模拟用户的输入的数据如下 因为用户输入的都是字符串

String name = "XML基础";
String author = "焦宁波";
String price = "99.99";
String date = "2013-01-04";

Book book = new Book();

BeanUtils只支持四形八种基本变量  所以其他构造类型 需要我们自己写转换类


// 注册一个自己的转换器

/*
* ConvertUtils.register(new Converter() {

* // 接口的方法不需要自己调用 称为回掉方法

* @Override public Object convert(Class type, Object value) {
* System.out.println(value + type.toString()); if (value == null) {
* return null; } String data = (String) value; SimpleDateFormat
* format=new SimpleDateFormat("yyyy-MM-dd"); Date date=null;

* try { date=format.parse(data); return date;

* } catch (ParseException e) { e.printStackTrace(); return null; }


* }

* }, Date.class);
*/


当然这种转换比较麻烦  beanUtils封装了一些常用的转换器



ConvertUtils.register(new DateLocaleConverter(), Date.class);





BeanUtils.setProperty(book, "name", name);
BeanUtils.setProperty(book, "author", author);
BeanUtils.setProperty(book, "price", price);
BeanUtils.setProperty(book, "date", date);


// 实现属性封装数据的一个拷贝
Book copy = new Book();
System.out.println(copy);
PropertyUtils.copyProperties(copy,book);
System.out.println(copy);

一次性封装所有数据


@Test
	public void setValues() throws Exception{
		User u = new User();
//		BeanUtils.setProperty(u, "name", new String[]{"Rose","Jack"});
//		System.err.println(u);
		
		Map<String,Object> o = new HashMap<String, Object>();
		o.put("name", "KDKDKD");
		o.put("age", "8888");
		
		BeanUtils.populate(u,o);
		System.err.println(u);
	}

使用beanutils一次封装所有参数

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		Map<String,String[]> map = request.getParameterMap();
		User user = new User();
		try {
			BeanUtils.populate(user, map);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		System.err.println("usre is :"+user);
	}

如和去除所有的trycach。。。

public class BeanUtils {
	public static <T>T populate(T t,Map<String,? extends Object> param){
		try{
			org.apache.commons.beanutils.BeanUtils.populate(t, param);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		return t;
	}
	public static <T>T populate(Class<T> cls,Map<String,? extends Object> param){
		T t = null;
		try {
			t = populate(cls.newInstance(),param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}
}


所需工具
 下载地址 www.apache.org











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值