zoukankan      html  css  js  c++  java
  • 今日总结

    2020年10月17日:

    关于昨日的BeanUtils.populate方法,具体详解如下:

    首先,需要导包:org.apache.commons.beanutils.BeanUtils

    原理:BeanUtils.populate( Object bean, Map properties )。这个方法会遍历map<key,value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。

    部分代码如下:

    public static <T> T request2Bean(HttpServletRequest request,Class<T>  beanClass){
    try{
    T bean = beanClass.newInstance();
    //得到request里面所有数据
    Map map = request.getParameterMap();
    //map{name=aa,password=bb,birthday=1990-09-09}  bean(name=aa,password=dd,birthday=Date)

    ConvertUtils.register(new Converter(){


    public Object convert(Class type, Object value) {
    if(value==null){
    return null;
    }
    String str = (String) value;
    if(str.trim().equals("")){
    return null;
    }

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {
    return df.parse(str);
    } catch (ParseException e) {
    throw new RuntimeException(e);
    }
    }
    }, Date.class);
    BeanUtils.populate(bean, map);   
    return bean;
    }catch (Exception e) {
    throw new RuntimeException(e);
    }

    }

    此段代码的原理:

    这是beanUtils工具包中的一个方法,该方法用来转换类型,ConvertUtils.register函数支持8种基本类型与String自动转换。

    用来将前台jsp页面或者html页面的传过来的参数通过parameterMap封装在map集合中,通过映射,将页面的内容先使用request获得,然后将之转换为Map,然后就可以使用BeanUtils.populate(Object bean, Map properties)方法将前台jsp或者html页面的数据属性映射到bean中,也就相当于将数据封装到bean中。随后,我们就可以通过bean.getXxx()方法来获取相应属性的值了。

  • 相关阅读:
    Javascript 返回上一页
    html中link和import方式导入CSS文件的区别
    Leecode no.76 最小覆盖子串
    Leecode no.344 反转字符串
    Leecode no.167 两数之和 II 输入有序数组
    Leecode no.567 字符串的排列
    遍历目录和文件信息
    JAVASCRIPT显示农历的日历
    asp.net上传图片加水印(c#)
    asp.net XML操作类
  • 原文地址:https://www.cnblogs.com/yitiaokuailedexiaojingyu/p/14110279.html
Copyright © 2011-2022 走看看