Apache common beanutils 2

Source: Internet
Author: User
Tags access properties
Many of the well-developed easy-to-use components under Jakarta commons should be discussed in net FTP, but when you connect to the commons webpage, it will surely be shocked, wow, how can there be so many components that are already under development, and projects that are under sandbox (R & D)? So how to make good use of them becomes a matter of weeks in a row, topics that will be discussed !!
 

Commons Overview
Currently, release has been developed for beanutils, betwixt, CLI, collections, DBCP, digester, discovery, El, fileupload, httpclient, jelly, jexl, jxpath, Lang, Latka, logging, modeler, net, pool, validator, etc.

Each version is not the same and may be updated at any time. As for the official version that has not been released, some projects may be in use !! It is also possible that some components made by other projects can be shared. For example, resources (resource bundle component) used by struts are also included in sandbox R & D, prepare the release to better match the components of all projects.

Why does Jakarta use the Commons project? I hope you don't need to develop the same components again to achieve reusable !! They all have easy-to-use features and are also the masterpiece of Jakarta Committer. Therefore, this open source project cannot be mistaken !! Dear Java compatriots .................

Beanutils Introduction
I have been hesitating for a long time when I choose which component I want to introduce first, because every component is the essence and cannot be decided for a long time. Therefore, I have to follow whether to release and then follow the letter sequence, I hope you can understand the sorting ....

Why does beanutils need to be developed? Every engineer may write getters and setters while writing JavaBean, that is, getxxx () and setxxx () methods, but when your object is generated dynamically, maybe it is using a file, or maybe it is another reason, how do you access the data !!

For several examples, you may use beanutils. Of course, this is an existing project.

  • BSF: between script language and Java object model
  • Velocity/jsp: use template to create similar web pages
  • Jakarta taglibs/struts/cocoon: Create your own special tag libraries for JSP or xsp
  • Ant build. xml/tomcat server. xml: configuration Resources)

You can use Java. Lang. reflect and Java. beans in the Java API to exchange data ~~ However, it is a little difficult =. = "", but beanutils will reduce your development time !!

The latest version is 1.6.1 (2003/2/18 released ),
Download location: Binary & Source

Beanutils API Introduction
Beanutils's main Java APIs include a total of four packages.

  1. Org. Apache. commons. beanutils
  2. Org. Apache. commons. beanutils. Converters
  3. Org. Apache. commons. beanutils. locale
  4. Org. Apache. commons. beanutils. locale. Converters

In fact, except for the first item, other versions are added later. Converters specifically processes the conversion of different incoming objects. locale is used for international processing, so I will focus on the first item !!

Among them, the most commonly used classes are propertyutils, convertutils, and dynabeans (which should be familiar with Struts DYNAFORM)

 

Beanutils. propertyutils Introduction
Basically, I assume that everyone has no problem with the development of JavaBean, that is, they know what getters and setters are. Let's first assume that the employee class


    public class Employee {
        public Address getAddress(String type);
        public void setAddress(String type, Address address);
        public Employee getSubordinate(int index);
        public void setSubordinate(int index, Employee subordinate);
        public String getFirstName();
        public void setFirstName(String firstName);
        public String getLastName();
        public void setLastName(String lastName);
    }

There are three methods in propertyutils.

  • Simple-If you use primitive syntax, such as int, string, or other self-developed objects, you only need a single object to obtain data.

    Propertyutils. getsimpleproperty (Object bean, string name)

    Propertyutils. setsimpleproperty (Object bean, string name, object value)


        Employee employee = ...;
        String firstName = (String)
          PropertyUtils.getSimpleProperty(employee, "firstName");
        String lastName = (String)
          PropertyUtils.getSimpleProperty(employee, "lastName");
     .............
        PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
        PropertyUtils.setSimpleProperty(employee, "lastName", lastName);
     
  • Indexed-If you use objects produced by collection or list, you only need to use an index value to obtain the object state.

    Propertyutils. getindexedproperty (Object bean, string name)

    Propertyutils. getindexedproperty (Object bean, string name, int index)

    Propertyutils. setindexedproperty (Object bean, string name, object value)

    Propertyutils. setindexedproperty (Object bean, string name, int index, object value)


        Employee employee = ...;
        int index = ...;
        String name = "subordinate[" + index + "]";
        Employee subordinate = (Employee)
          PropertyUtils.getIndexedProperty(employee, name);

        Employee employee = ...;
        int index = ...;
        Employee subordinate = (Employee)
          PropertyUtils.getIndexedProperty(employee, "subordinate", index);
     
  • Mapped-If you use the objects extended by map, you only need to use a key value to obtain the data.

    Propertyutils. getmappedproperty (Object bean, string name)

    Propertyutils. getmappedproperty (Object bean, string name, string key)

    Propertyutils. setmappedproperty (Object bean, string name, object value)

    Propertyutils. setmappedproperty (Object bean, string name, string key, object value)


        Employee employee = ...;
        Address address = ...;
        PropertyUtils.setMappedProperty(employee, "address(home)", address);

        Employee employee = ...;
        Address address = ...;
        PropertyUtils.setMappedProperty(employee, "address", "home", address);

     

But if you are a nested data structure, how do you obtain the data you want?

Propertyutils. getnestedproperty (Object bean, string name)

Propertyutils. setnestedproperty (Object bean, string name, object value)

You only need to simply use "." to get the data you want.


    String city = (String)
      PropertyUtils.getNestedProperty(employee, "address(home).city");

Remember, beanutils is designed to be used as you like, so index and mapped can certainly be used like this.


    Employee employee = ...;
    String city = (String) PropertyUtils.getProperty(employee,
      "subordinate[3].address(home).city");

 

Beanutils. dynabean and beanutils. dynaclass Introduction
All dynamic JavaBean interfaces are dynabean or dynaclass, and dynaproperty class may be used to access properties. why do we need to use dynamic JavaBean? For example, the data you extract from the database may sometimes contain three or four columns, if we want to write a class for every bean, we will be very tired. So we will set its attributes for every JavaBean, then, propertyutils can be used to extract the value, which can reduce the development work hours. in the struts course, many people asked me if every actionform must be written into a Java file. Of course, this is not required. Otherwise, one webpage and one actionform (assuming they are different ), that's a waste of time. So we all use org. Apache. Struts. Action. dynaactionform !!

Mutabledynaclass (since $1.5) is a new dynaclass to dynamically adjust properties!

  • Basicdynabean and basicdynaclass-Basic Dynamic types

    Basicdynaclass (Java. Lang. string name, java. Lang. Class dynabeanclass, dynaproperty [] properties)

    Basicdynabean (dynaclass)


        DynaProperty[] props = new DynaProperty[]{
            new DynaProperty("address", java.util.Map.class),
            new DynaProperty("subordinate", mypackage.Employee[].class),
            new DynaProperty("firstName", String.class),
            new DynaProperty("lastName",  String.class)
          };
        BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);

        DynaBean employee = dynaClass.newInstance();
        employee.set("address", new HashMap());
        employee.set("subordinate", new mypackage.Employee[0]);
        employee.set("firstName", "Fred");
        employee.set("lastName", "Flintstone");

     
  • Resultsetdynaclass (wraps resultset in dynabeans)-Use the dynamic JavaBean of resultset

    Resultsetdynaclass (Java. SQL. resultset)

    Resultsetdynaclass (Java. SQL. resultset, Boolean lowercase)

    If lowercase is set to false, the returned data field will prevail based on the data returned by JDBC. Default is true.


     Connection conn = ...;
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery
     ("select account_id, name from customers");
     Iterator rows = (new ResultSetDynaClass(rs)).iterator();
     while (rows.hasNext()) {
      DynaBean row = (DynaBean) rows.next();
      System.out.println("Account number is " +
            row.get("account_id") +
            " and name is " + row.get("name"));
     }
     rs.close();
     stmt.close();
     
  • Rowsetdynaclass (disconnected resultset as dynabeans)-Use rowset's dynamic JavaBean

    Rowsetdynaclass (Java. SQL. resultset)

    Rowsetdynaclass (Java. SQL. resultset, Boolean lowercase)

    If lowercase is set to false, the returned data field will prevail based on the data returned by JDBC. Default is true.


        Connection conn = ...;  // Acquire connection from pool
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT ...");
        RowSetDynaClass rsdc = new RowSetDynaClass(rs);
        rs.close();
        stmt.close();
        ...;                    // Return connection to pool
        List rows = rsdc.getRows();
        ...;                   // Process the rows as desired

     
  • Wrapdynabean and wrapdynaclass-Packaged dynamic JavaBean

    If you are very impressed with the powerful functions of dynabean, And the an at hand cannot be used at will, you can wrap it up ....

    Wrapdynaclass (Java. Lang. Class beanclass)

    Wrapdynabean (Java. Lang. object instance)

    Convertingwrapdynabean (Java. Lang. object instance)



        MyBean bean = ...;
        DynaBean wrapper = new WrapDynaBean(bean);
        String firstName = wrapper.get("firstName");

     

 

Beanutils. convertutils Introduction
In many cases, for example, in Struts framework, the request. getparameter parameter is often used and must be converted to the correct data type. Therefore, convertutils is used to process these actions.

Convertutils (). Convert (Java. Lang. Object value)

Convertutils (). Convert (Java. Lang. String [] values, java. Lang. Class clazz)

Convertutils (). Convert (Java. Lang. String Value, java. Lang. Class clazz)


    HttpServletRequest request = ...;
    MyBean bean = ...;
    HashMap map = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      map.put(name, request.getParameterValues(name));
    }
    BeanUtils.populate(bean, map);// it will use ConvertUtils for convertings

 

Currently, the supported types are:

  • Sjava. Lang. bigdecimal
  • Java. Lang. biginteger
  • Boolean and Java. Lang. Boolean
  • Byte and Java. Lang. byte
  • Char and Java. Lang. Character
  • Java. Lang. Class
  • Double and Java. Lang. Double
  • Float and Java. Lang. Float
  • INT and Java. Lang. Integer
  • Long and Java. Lang. Long
  • Short and Java. Lang. Short
  • Java. Lang. String
  • Java. SQL. Date
  • Java. SQL. Time
  • Java. SQL. Timestamp

You can also create your own converter.


   Converter myConverter =
    new org.apache.commons.beanutils.converter.IntegerConverter();


   ConvertUtils.register(myConverter, Integer.TYPE);    // Native type


   ConvertUtils.register(myConverter, Integer.class);   // Wrapper class
 
Source: http://www.3doing.net/forums/printpage.asp? Boardid = 1 & id = 264

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.