BeanUtils工具使用

来源:互联网 发布:奇点大学 知乎 编辑:程序博客网 时间:2024/06/07 01:59

  • BeanUtils工具使用

BeanUtils工具使用

​ BeanUtils主要解决的问题是:把对象的属性数据封装到对象中。

​ 即:我们从jsp页面中获取到的请求参数都是String类型的,封装到javabean时需要转换成不同的数据类型,此时通过beanutils可以帮助我们解决数据类型转换问题。

​ BeanUtils的使用需要两个jar包:

  • commons-beanutils-1.9.2.jar 下载地址: http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi
  • commons-logging.jar 下载地址: https://commons.apache.org/proper/commons-logging/download_logging.cgi

​ 主要使用BeanUtils中的.populate(bean,Map)方法。其中bean指的是需要封装到的javabean对象,Map是指从jsp页面中获取的请求参数Map集合,通过request.getParameterMap()获取。使用步骤如下:

    Customer c=new Customer();    BeanUtils.populate(c, request.getParameterMap());    System.out.println(c);

​ 此时输出的对象c就是通过BeanUtils封装好每个数据类型的对象。

​ 一般情况下直接正常使用即可,但是可能遇到的特殊情况有:

1、获取的请求参数与javabean的属性值个数不同

​ 解决办法:将无法获取的请求参数通过set方法进行设定之后再进行populate()封装

2、获取的日期类型,BeanUtils无法进行转换

​ 解决办法:通过DateConverter进行日期类型的转换

    DateConverter dc=new DateConverter();//类型转换器    dc.setPattern("yyyy-MM-dd");    ConvertUtils.register(dc, java.util.Date.class);    BeanUtils.populate(c, request.getParameterMap());
原创粉丝点击