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());
        }
    
    }
  • 相关阅读:
    MYSQL设置允许所有访问
    解决ios端的H5,input有阴影的问题
    linux查看某个时间段的日志(sed -n)
    centos如何创建自启动脚本
    laravel做数据迁移的时候进行表的注释
    taro编译微信小程序,报错“未找到setmap.json文件”
    java百科常识
    spring自动装配
    top命令内容详解
    jemter 随机取数组里面的值放入请求
  • 原文地址:https://www.cnblogs.com/liqiu/p/3618655.html
Copyright © 2011-2022 走看看