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());
        }
    
    }
  • 相关阅读:
    markdown基础使用技巧
    用ps实现提高照片的清晰度
    正则表达式匹配:中、日、韩文
    解决"$ is not defined" 亲自体验
    [NLP] 相对位置编码(一) Relative Position Representatitons (RPR)
    [NLP] cs224n-2019 Assignment 1 Exploring Word Vectors
    [Deep Learning] GELU (Gaussian Error Linerar Units)
    [Python] 等号赋值, copy, deepcopy的区别
    [微积分] 利用极坐标计算二重积分
    [c++] C++多态(虚函数和虚继承)
  • 原文地址:https://www.cnblogs.com/liqiu/p/3618655.html
Copyright © 2011-2022 走看看