BeanUtils.populate()方法

在使用request获取表单数据之后,使用BeanUtils.populate()方法来快速给javaBean对象赋值的情况下,如果表单中含有javaBean中没有的属性的键对值的话,那么就会报错。 

为了防止这种情况

1,确保表单中只有javaBean对象的属性

2,如果有其它属性的话,需要把javaBean对象中的属性给单独拿出来,再调用BeanUtils.populate()方法赋值

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//创建一个测试用的userTest的JavaBean类
		UserTest us = new UserTest();
		String teString = "xixi";
		String name = "mingzi";
		String age = "11";
		String addr = "addr123";
		String sclool = "hebei";
		//先创建一个map,模拟request.getParameterMap();方法返回的map对象,其中杂项1,杂项2为干扰项
		//如果带着杂项1,杂项2使用BeanUtils.populate()方法给user对象赋值的话,会报错,所以要把他删掉
		Map<String, String> map = new HashMap<String,String>();
		map.put("zaxiang", teString);
		map.put("name", name);
		map.put("age", age);
		map.put("addr", addr);
		map.put("sclool", sclool);
		map.put("zaxiang2", "heiehi");
		//测试用map有没有正常把值录入进去
		for(Entry<String, String> entry:   map.entrySet()) {
			System.out.println(entry.getKey() + " ___" + entry.getValue());
		}
		
		//思路:先获取user中的所有有效属性,然后根据属性,把map中对应的键对值拿出来,拿出来后放到新生成的map来调用BeanUtils.populate()方法给user对象赋值
		//创建了一个用于存放user中有效数据的一个map集,NewMap的缩写nm
		Map<String, String> nm = new HashMap<String,String>();
		// 通过反射的方法 , 先获取user中有效属性的方法:先通过user对象的.getClass()方法获取到user的class
		Class<?> cl = us.getClass();
		//然后通过class中的.getDeclaredFields()方法获取User中属性的集合,返回来的是Field对象。
		Field[] fie = cl.getDeclaredFields();
		//遍历所有属性的集合,判断原来的map中有没有对应的键,如果有的话,就添加到nm中
		for(Field fie1 :  fie) {
			String usNam = fie1.getName();
			if(map.containsKey(usNam)) {
				nm.put(usNam, map.get(usNam));
			}
		}
		//测试用,遍历的处理之后的数组
		for(Entry en:nm.entrySet()) {
			Object key = en.getKey();
			System.out.println(key + "----" + en.getValue());
		}
		//处理之后的数组没问题了,就可以通过BeanUtils.populate()方法给user对象赋值了
		try {
			BeanUtils.populate(us, nm);
			System.out.println(us.toString());
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值