BeanUtils组件

一 简介
1 程序中对javabean的操作很频繁, 所以apache提供了一套开源的api,方便对javabean的操作!即BeanUtils组件。
BeanUtils组件, 作用是简化javabean的操作!
2 使用组件
BeanUtils组件 maven下载:

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.8.3</version>
</dependency>

logging组件(日志支持包) maven下载:

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.3</version>
</dependency>

如果缺少日志包将会报错

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
    at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
    at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)

二 基本用法
方法1: 对象属性的拷贝
BeanUtils.copyProperty(student, "name", "jack");
BeanUtils.setProperty(student, "password", 123);
方法2: 对象的拷贝
BeanUtils.copyProperties(newStudent, student);
方法3: map数据拷贝到javabean中
【注意:map中的key要与javabean的属性名称一致】
BeanUtils.populate(studentMap, map);

import entity.Student;
import org.apache.commons.beanutils.BeanUtils;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by pc on 2017/7/25.
 */
public class BeanUtilsTest {
    public  static void main(String [] args){
        try {
            //a.基本操作
        Student student=new Student();
        //student.setId(1);
        //student.setName("Jack");
        //student.setPassword("123");
            //b.BeanUtils组件实现对象属性拷贝
        BeanUtils.copyProperty(student,"id",1);
        BeanUtils.setProperty(student,"name","Tom");
            //总结1: 对于基本数据类型,会自动进行类型转换

            //c.对象的拷贝
            Student newStudent =new Student();
            BeanUtils.copyProperties(newStudent,student);

            //d.map数据,拷贝对象
            Student studentMap=new Student();
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("id",02);
            map.put("name","Wang");
            map.put("password","123");
            //注意:map中的key要与javabean的属性名称一致
            BeanUtils.populate(studentMap,map);
            //测试
            System.out.println(studentMap.getName());
            System.out.println(studentMap.getId());
            System.out.println(studentMap.getPassword());

        } catch (Exception e) {
            throw new RuntimeException();
        }


    }
}

实例,日期类型的拷贝

package utils;

import entity.Student;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by pc on 2017/7/25.
 */
public class BeanUtilsTime {
    public static void main(String [] args) throws Exception{
        //模拟表单
        int id=1;
        String name="Jack";
        String password="123";
        String brith="1997-01-02";
        //对象
        Student student=new Student();
        //注册类型转换器:1.自定义方法
        ConvertUtils.register(new Converter() {
            //转换的内部实现方法,需要重写
            public Object convert(Class type, Object value) {
                //判断
                if (type!= Date.class){
                    return  null;
                }
                if (value == null || "".equals(value.toString().trim())){
                    return null;
                }
                try {
                    //字符串转日期
                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
                    return sdf.parse(value.toString());
                }catch (Exception e){
                    throw  new RuntimeException(e);
                }

            }
        },Date.class);
        // 把表单提交的数据,封装到对象中
        BeanUtils.copyProperty(student,"id",id);
        BeanUtils.copyProperty(student,"name",name);
        BeanUtils.copyProperty(student,"password",password);
        BeanUtils.copyProperty(student,"brith",brith);
        System.out.println(student);
    }
    public void test() throws Exception {
        // 模拟表单数据
        int id=1;
        String name="Jack";
        String password="123";
        String brith="1997-01-02";

        // 对象
        Student student1 = new Student();

        // 注册日期类型转换器:2, 使用组件提供的转换器工具类
        ConvertUtils.register(new DateLocaleConverter(), Date.class);

        // 把表单提交的数据,封装到对象中
        BeanUtils.copyProperty(student1, "id", id);
        BeanUtils.copyProperty(student1, "name", name);
        BeanUtils.copyProperty(student1, "password", password);
        BeanUtils.copyProperty(student1, "birth", brith);

        //------ 测试------
        System.out.println(student1);
    }

}

三 应用(javaBean操作封装)

package utils;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by pc on 2017/7/25.
 */
public class WebUtils {
    public static <T> T copyToBean(HttpServletRequest request,Class<T> tClass){
    try {
        //创建对象
        T t=tClass.newInstance();
        //获取所有表单元素的名称
        Enumeration<String> enumeration=request.getParameterNames();
        //遍历
        while (enumeration.hasMoreElements()){
            //获取表单元素名称
            String name=enumeration.nextElement();
            //获取名称对应的值
            String value=request.getParameter(name);
            //把指定属性名称对应的值进行拷贝
            BeanUtils.copyProperty(t,name,value);
        }
        return t;
    }catch (Exception e){
        throw new RuntimeException(e);
    }

    }
}

测试:Student student= WebUtils.copyToBean(request,Student.class);

封装方法二

 public static <T> T copyToBean(HttpServletRequest request, Class<T> clazz) {
        try {
            // (注册日期类型转换器)
            // 创建对象
            T t = clazz.newInstance();
            BeanUtils.populate(t, request.getParameterMap());
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,976评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,249评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,449评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,433评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,460评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,132评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,721评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,641评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,180评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,267评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,408评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,076评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,767评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,255评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,386评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,764评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,413评论 2 358

推荐阅读更多精彩内容