|
Home TOC Index |
|
Search
Feedback |
Retrieving JavaBeans Component Properties
There are several ways to retrieve JavaBeans component properties. Two of the methods (the
jsp:getPropertyelement and an expression) convert the value of the property into aStringand insert the value into the current implicitoutobject:For both methods,
beanNamemust be the same as that specified for theidattribute in auseBeanelement, and there must be agetPropNamemethod in the JavaBeans component.If you need to retrieve the value of a property without converting it and inserting it into the
outobject, 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.jspuses the form<jsp:getProperty name="currency" property="format"/>whereas
bookstore2/showcart.jspuses the form<%= currency.getFormat() %>The Duke's Bookstore application page
bookstore2/showcart.jspuses 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.jspreplaces 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:useBeantag are stored as attributes of the scope objects and can be accessed byjsp:[get|set]Propertytags 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.
|
Home TOC Index |
|
Search
Feedback |