实现MyBeanUtils将请求数据封装到JavaBean中

一. 作用

将请求中的数据,自动获取,并封装到给出的,javabean类中,返回存储着数据的对象:
如下所示:

  	 //request :  ?title=aaaa&summary=xxxx&content=sfsfdsfsdf

 	 //	请求的参数自动封装到实体类中
  		News news = new News();
		String title = req.getParameter("title");
		String content = req.getParameter("content");
		news.setTitle(title);
		news.setContent(content);
		return news;

二. 实现

  1. 获取 key-value的键值对,集合
  2. 得到key对应的方法
  3. 将value 转化为对应方法的参数属性
  4. 将参数放入对象中
public class MyBeanUtils {
	public static <T> T requestToBean(Class<T> cls,HttpServletRequest request) {
		try {
			T obj = cls.getDeclaredConstructor().newInstance();
			//获取参数  ?title=aaaa&content=xxxxxx&xx=yyyy
			Map<String, String[]> paramMap =  request.getParameterMap();
			//遍历Map
			Set<Entry<String, String[]>> set = paramMap.entrySet();
			
			for (Entry<String, String[]> entry : set) {
				String name = entry.getKey();  //属性名
				String[] value = entry.getValue();
				try {
					//根据属性名获取setter方法  title----setTitle()
					String setName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);  //setName = "setTitle";
					Class<?> type = cls.getDeclaredField(name).getType();  //获取对应的属性的类型
					// 方法名  参数类型  
					Method method = cls.getDeclaredMethod(setName, type);
					// obj.setTitle(value);
					Object val = value[0];
					// 转型问题:
					if(type==int.class || type==Integer.class) {
						val = Integer.parseInt(val.toString());
					}else if(type==float.class || type==Float.class) {
						val = Float.parseFloat(val.toString());
					}
					//obj.setTitle(value);
					method.invoke(obj, val);
				}catch (Exception e) {
					
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值