The J2EETM Tutorial
Home
TOC
Index
PREV TOP NEXT Search
Feedback

Retrieving JavaBeans Component Properties

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

For both methods, beanName must be the same as that specified for the id attribute 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"/>
 

whereas 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 Chapter 13) 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 12-1 summarizes where various types of objects are stored and how those objects can be accessed from a JSP page. Objects created by the jsp:useBean tag 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.

Figure 12-1 Accessing Objects From a JSP Page

Home
TOC
Index
PREV TOP NEXT Search
Feedback