zoukankan      html  css  js  c++  java
  • 利用Common-BeanUtils封装请求参数

    一、BeanUtils介绍

          commons-beanutils是利用反射机制对JavaBean的属性进行处理,提供了对于JavaBean的各种处理方法。众所周知,一个JavaBean通常包含了大量的属性,而对于JavaBean的处理导致大量get/set方法的堆积,使用BeanUtils能简化我们的代码量,将我们的双手从get/set方法中解放出来,让我们节省时间去搬其它的砖头。

    二、BeanUtils基本使用

          1,通过BeanUtils类可以直接get和set一个属性的值,方法如下(第一个参数是JavaBean对象,第二个参数是要操作的属性名):

    getSimpleProperty(Object bean, String name)
    Return the value of the specified simple property of the specified bean, converted to a String.
    
    setProperty(Object bean, String name, Object value)
    Set the specified property value, performing type conversions as required to conform to the type of the destination property.

      2,一个更常用更重要的方法是:copyProperties()

    copyProperties(Object dest, Object orig)
    Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
    
    copyProperty(Object bean, String name, Object value)
    Copy the specified property value to the specified destination bean, performing any type conversion that is required.

    需要注意的是这种copy都是浅拷贝,复制后的两个Bean的同一个属性可能拥有同一个对象的引用。所以在使用时要小心,特别是对于属性为自定义类的情况。

    三、封装web请求参数

      定义一个静态方法copyParmas(),用于将request请求参数值赋给相应的bean的对应属性,若请求参数名与bean属性名不匹配,该值会被舍弃。

        public static Object copyParams(Class targetClass, HttpServletRequest request){
            Object bean = null;
            try {
                bean = targetClass.newInstance();
                Map params = request.getParameterMap();
                Set set = params.entrySet();
                for(Iterator iterator = set.iterator();iterator.hasNext();){
                    Entry entry = (Entry) iterator.next();
                    String name = (String) entry.getKey();
                    Object[] values = (Object[]) entry.getValue();
                    
                    if(values!=null){
                        if(values.length == 1){
                            BeanUtils.copyProperty(bean, name, values[0]);
                        }else {
                            BeanUtils.copyProperty(bean, name, values);
                        }
                    }
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return bean;
        }
    View Code

    四、copyProperties性能

      不幸的是Commons BeanUtil的copyProperties性能较差,而直接get/set虽然丑陋麻烦,但是性能很好。具体情况可参看文章:http://tntest.iteye.com/blog/399577 。

  • 相关阅读:
    一千行 MySQL 学习笔记
    linux学习(二)
    linux学习(二)
    内联元素
    内联因素1.默认内容撑开盒子大小
    定位absolute使内联支持宽高(块属性变为内联,内容默认撑开)margin auto 失效
    over
    float浮动问题:会造成父级元素高度坍塌;
    float的元素脱离文档流,但不完全脱离,只是提升了半层;
    float了的元素和内联元素不支持margin:auto
  • 原文地址:https://www.cnblogs.com/jianzhi/p/3351382.html
Copyright © 2011-2022 走看看