java_EE 自动封装表单数据

来源:互联网 发布:网络yy语音授课是什么 编辑:程序博客网 时间:2024/05/29 17:51

1 所需要的jar包
2 常用的方法
2.1BeanUtils.setProperty(bean, name, value);
其中bean是指你将要设置的对象,name指的是将要设置的属性(写成”属性名”),value(从配置文件中读取到到的字符串值)
2.2BeanUtils.copyProperties(bean, name, value),
和上面的方法是完全一样的。使用哪个都可以

public class Person private int age;private String name;private Date birth;
    Person p1=new Person();        String name="王帅";        String age="20";        String birth="1999-12-12";        ConvertUtils.register(new DateLocaleConverter(), Date.class);//注释掉就会报错        BeanUtils.setProperty(p1, "name", name);        BeanUtils.setProperty(p1, "age", age);        BeanUtils.setProperty(p1, "birth", birth);        System.out.println(p1);    }说明:注释掉报错原因 无法将1999-12-12转换为日期类 因为person属性是date类型,也就是说 只能对基本类型经行转换, 因为你存的王帅 20 都是 String 类型,但是该类都可以帮你转换成person类相应的类型, 所以注册一个日期类转换对象,也就是基本类型 不用 注册器,直接帮你转换成javaBean相应的类型,}//结果:Person [age=20, name=王帅, birth=Sun Dec 12 00:00:00 CST 1999]

2.3ConvertUtils.register(Converter converter , ..)
当需要将String数据转换成引用数据类型(或者自定义数据类型时),需要使用此方法实现转换。
2.4BeanUtils.populate(bean,Map)实现对javaBean的封装 从表单获取的数据
其中Map中的key必须与目标对象中的属性名相同,否则不能实现拷贝。
提示:在获取表单的时候,直接可以
ConvertUtils.register(new DateLocaleConverter(), Date.class);//不灵活 下文可以自定义时间转换器
BeanUtils.populate(us, request.getParameterMap());
// request.getParameterMap(是把表单的数据封装成为一个map集合,得到的是一个集合

    HashMap<String ,String> map =new HashMap<String,String>();        map.put("name", "王帅");        map.put("age", "20");        map.put("birth", "2017年12月10日");        //自定义一个日期转换器        ConvertUtils.register(new Converter() {            @Override            public Object convert(Class type, Object value) {                // TODO 自动生成的方法存根                System.out.println(value);                 if(type != Date.class)  return null;                    if (value == null || "".equals(value.toString().trim())) {                        return null;                    }                    System.out.println("进来了");               SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");                    Date date = null;                    try {                         date = dateFormat.parse((String)value);                         System.out.println(date);                    } catch (ParseException e) {                        throw new RuntimeException(e);                    }                    return date;                }        }, Date.class);        BeanUtils.populate(p1,map);   System.out.println(p1);    }        结果展示:        20171210日     进来了      Sun Dec 10 00:00:00 CST 2017

2.5BeanUtils.copyProperties(newObject,oldObject),
实现对象的拷贝