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

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.

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.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.187.108