zoukankan      html  css  js  c++  java
  • BeanUtils使用

    JAVA在Web开发项目中,经常会接收各种参数,并将这些参数保存到对象里面去,比如,http://127.0.0.1/Servlet/?username=liqiu&password=123456&age=29。需要将这些内容保存在User对象里面去,User.java代码如下:

    public class User {
        private String username;
        private String password;
        private int age;
    public String getUsername() {
            return username;
        }
    .............................
    }

    那么,如果不使用BeanUtils,需要一个参数一个参数的判断,转换和赋值,反之:

            Map map = request.getParameterMap();
            User user = new User();
            try {
                BeanUtils.populate(user, map);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    当然也有略复杂的情况,比如传输时间类型的数据

    package com.taobao.beanutils;
    .............................................public class Demo01 {
    // 自定义转换器
        @Test
        public void test2() throws Exception {
            Person p = new Person();
            ConvertUtils.register(new Converter() {
    
                @Override
                public Object convert(Class type, Object value) {
                    if (value == null) {
                        return null;
                    }
                    if (!(value instanceof String)) {
                        throw new ConversionException("conversion error");
                    }
                    String str = (String) value;
                    if (str.trim().equals("")) {
                        return null;
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        return sdf.parse(str);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
    
                }
    
            }, Date.class);
            BeanUtils.setProperty(p, "birth", "2011-10-10");
            System.out.println(p.getBirth().toLocaleString());
        }
    
        // 使用内置的转换器
        @Test
        public void test3() throws Exception {
            Person p = new Person();
            ConvertUtils.register(new DateLocaleConverter(), Date.class);
            BeanUtils.setProperty(p, "birth", "2011-10-10");
            System.out.println(p.getBirth().toLocaleString());
        }
    
    }
  • 相关阅读:
    shell学习之杂项
    boot小知识
    记一个数组的问题
    lnmp安装exif扩展
    国内的Git比GitHub快
    重用思想,要有识别出好代码的眼睛,识别出腐朽代码的眼睛
    CSS3之超出隐藏
    如何测量设计图中图片的尺寸,像素
    Linux 软链接操作项目
    微信小程序申请。很蛋疼的流程。
  • 原文地址:https://www.cnblogs.com/liqiu/p/3618655.html
Copyright © 2011-2022 走看看