8.3 Using JavaBeans with Struts Tags


In many cases, you'll use the tags from the various tag libraries in conjunction with JavaBeans. The JavaBeans may be ActionForms, whose properties correspond to input fields in the HTML form. In other cases, however, the beans will be ordinary value objects from the model layer. These beans can be in any scope: page, request, session, or application.

There are three ways to access the properties of a JavaBean:

  • Accessing simple properties

  • Accessing nested properties

  • Accessing indexed properties

8.3.1 Accessing Simple Properties

Accessing simple bean properties works similarly to the JSP <jsp:getProperty> action. A reference to a property named "firstName" is converted into a method call to getFirstName() or setFirstName(value), using the standard JavaBeans specification naming conventions for bean properties.

Struts uses the Java introspection APIs to identify the names of the actual property getter and setter methods, so your beans can provide customized method names through the use of a BeanInfo class. See the JavaBeans specification, available at http://java.sun.com/products/javabeans, for more information.

8.3.2 Accessing Nested Properties

Nested references are used to access a property through a hierarchy of property names separated by periods (.), similar to the way that nested properties are accessed in JavaScript. For example, the following property reference:

property="user.address.city"

is translated into the equivalent Java expression:

getUser( ).getAddress( ).getCity( )

If a nested reference is used in a setter (such as when an input form is processed), the property setter is called on the last property in the chain. For the above property reference, the equivalent Java expression would be:

getUser( ).getAddress( ).setCity(value)

Nested properties are very convenient to use with custom tags. They almost always are used with the property attributes of the supported tags.

8.3.3 Accessing Indexed Properties

Subscripts can be used to access individual elements of properties whose values are actually arrays, or whose underlying JavaBeans offer indexed getter and setter methods. For example, the following property reference:

property="address[2]"

is translated into the equivalent Java expression:

getAddress(2);

while the same property reference in a setter would call the equivalent of:

setAddress(2, address)

As you can see from these examples, the subscripts used in indexed references are zero-relative (that is, the first element in an array is address[0]), just as is true in the Java language.



Programming Jakarta Struts
Programming Jakarta Struts, 2nd Edition
ISBN: 0596006519
EAN: 2147483647
Year: 2003
Pages: 180

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net