Retrieving JavaBeans Component Properties

Retrieving JavaBeans Component Properties

There are several ways to retrieve JavaBeans component properties. Two of the methods convert the value of the property into a String and insert the value into the current implicit out object: the jsp:getProperty element and an expression:

  • <jsp:getProperty name="beanName " property="propName "/>

  • <%= beanName .getPropName () %>

For both methods, beanName must be the same as that specified for the idattribute in a useBean element and there must be a getPropName method in the JavaBeans component.

If you need to retrieve the value of a property without converting it and inserting it into the out object, you must use a scriptlet:

<% Object o = beanName.getPropName(); %>

Note the differences between the expression and the scriptlet; the expression has an "=" after the opening "%" and does not terminate with a semicolon, as does the scriptlet.

The Duke's Bookstore application demonstrates how to use both forms to retrieve the formatted currency from the currency bean and insert it into the page. For example, bookstore3/showcart.jsp uses the form:

<jsp:getProperty name="currency" property="format"/>

while bookstore2/showcart.jsp uses the form:

<%= currency.getFormat() %>

The Duke's Bookstore application page bookstore2/showcart.jsp uses the following scriptlet to retrieve the number of books from the shopping cart bean and open a conditional insertion of text into the output stream:

    // Print a summary of the shopping cart 
    int num = cart.getNumberOfItems(); 
    if (num > 0) {

Although scriptlets are very useful for dynamic processing, using custom tags (see Custom Tags in JSP Pages (page 431)) to access object properties and perform flow control is considered to be a better approach. For example, bookstore3/showcart.jsp replaces the scriptlet with the following custom tags:

<bean:define id="num" name="cart" property="numberOfItems" /> 
<logic:greaterThan name="num" value="0" >

Figure summarizes where various types of objects are stored and how those objects can be accessed from a JSP page. Objects created by the jsp:useBeantag are stored as attributes of the scope objects and can be accessed by jsp:[get|set]Property tags and in scriptlets and expressions. Objects created in declarations and scriptlets are stored as variables of the JSP page's servlet class and can be accessed in scriptlets and expressions.

1. Accessing Objects from a JSP Page

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows