Home
TOC Index |
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 aString
and insert the value into the current implicitout
object: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/web/showcart.jsp
uses the form<jsp:getProperty name="currency" property="format"/>whereas
bookstore2/web/showcart.jsp
uses the form:<%= currency.getFormat() %>The Duke's Bookstore application page
bookstore2/web/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) to access object properties and perform flow control is considered to be a better approach. For example,
bookstore3/web/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 14-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 Index |
This tutorial contains information on the 1.0 version of the Java Web Services Developer Pack.
All of the material in The Java Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.