Home TOC |
![]() ![]() ![]() |
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 implicitout
object: thejsp:getProperty
element and an expression:For both methods,
beanName
must be the same as that specified for theid
attribute in auseBean
element and there must be aget
PropName
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
.get
PropName
(); %>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 pagebookstore2/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 461)) 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 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 byjsp:[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.
Home TOC |
![]() ![]() ![]() |