使用BeanUtils来进行对象的组装

字体大小: 中小 标准 ->行高大小: 标准
commons-beanutils组件是Jakarta Commons项目组中的一个,可以到Jakarta官网上去下载。

我们今天讨论的主要就是commons-beanutils中的BeanUtils这个类,这个类都是静态方法,

可以很方便的操纵各个JavaBean对象,包括获取属性、设置属性等,我们以例子来进行说明

。

TestBean.java

public TestBean 
{ 
    private String stringValue; 
  
    private int intValue; 
  
    public void setStringValue(String value) 
    { 
        this.stringValue = value; 
    } 
  
    public String getStringValue() 
    { 
        return this.stringValue; 
    } 
  
    public void setIntValue(int value) 
    { 
        this.intValue = value; 
    } 
  
    public int getIntValue() 
    { 
        return this.intValue; 
    } 
} 


那么我们就可以使用BeanUtils来对其进行设置值和获取值了。如下:


TestBean tb = new TestBean(); 
BeanUtils.setProperty(tb, "stringValue", "hello world!"); 
BeanUtils.setProperty(tb, "intValue", 123); 


在Servlet中直接与表单进行映射


TestBean tb = new TestBean(); 
BeanUtils.populate(tb, request.getParameterMap()); // 使用BeanUtils工具类来获取对

象的属性 System.out.println(BeanUtils.getProperty("stringValue")); 
System.out.print(BeanUtils.getProperty("intValue")); // 直接获取对象的属性 

System.out.println(tb.getStringValue()); 
System.out.println(tb.getIntValue()); 

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/70317.html