|
FAQ
History |
|
Search
Feedback |
JavaBeans Components in JSP Pages
JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component.
JavaServer Pages technology directly supports using JavaBeans components with JSP language elements. You can easily create and initialize beans and get and set the values of their properties. This chapter provides basic information about JavaBeans components and the JSP language elements for accessing JavaBeans components in your JSP pages. For further information about the JavaBeans component model see
http://java.sun.com/javase/technologies/desktop/javabeans/.JavaBeans Component Design Conventions
JavaBeans component design conventions govern the properties of the class and govern the public methods that give access to the properties.
A JavaBeans component property can be
There is no requirement that a property be implemented by an instance variable; the property must simply be accessible using public methods that conform to certain conventions:
In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters.
The Duke's Bookstore application JSP pages
enter.jsp,bookdetails.jsp,catalog.jsp, andshowcart.jspuse thedatabase.BookDBanddatabase.BookDetailsJavaBeans components.BookDBprovides a JavaBeans component front end to the access objectBookDBAO. Both beans are used extensively by bean-oriented custom tags (see Custom Tags in JSP Pages). The JSP pagesshowcart.jspandcashier.jspusecart.ShoppingCartto represent a user's shopping cart.The JSP pages
catalog.jsp,showcart.jsp, andcashier.jspuse theutil.CurrencyJavaBeans component to format currency in a locale-sensitive manner. The bean has two writable properties,localeandamount, and one readable property,format. Theformatproperty does not correspond to any instance variable, but returns a function of thelocaleandamountproperties.public class Currency { private Locale locale; private double amount; public Currency() { locale = null; amount = 0.0; } public void setLocale(Locale l) { locale = l; } public void setAmount(double a) { amount = a; } public String getFormat() { NumberFormat nf = NumberFormat.getCurrencyInstance(locale); return nf.format(amount); } }Why Use a JavaBeans Component?
A JSP page can create and use any type of Java programming language object within a declaration or scriptlet. The following scriptlet creates the bookstore shopping cart and stores it as a session attribute:
<% ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } %>If the shopping cart object conforms to JavaBeans conventions, JSP pages can use JSP elements to create and access the object. For example, the Duke's Bookstore pages
bookdetails.jsp,catalog.jsp, andshowcart.jspreplace the scriptlet with the much more concise JSPuseBeanelement:Creating and Using a JavaBeans Component
You declare that your JSP page will use a JavaBeans component using either one of the following formats:
or
<jsp:useBean id="beanName" class="fully_qualified_classname" scope="scope"> <jsp:setProperty .../> </jsp:useBean>The second format is used when you want to include
jsp:setPropertystatements, described in the next section, for initializing bean properties.The
jsp:useBeanelement declares that the page will use a bean that is stored within and accessible from the specified scope, which can beapplication,session,request, orpage. If no such bean exists, the statement creates the bean and stores it as an attribute of the scope object (see Using Scope Objects). The value of theidattribute determines the name of the bean in the scope and the identifier used to reference the bean in other JSP elements and scriptlets.
Note: In JSP Scripting Elements , we mentioned that you must import any classes and packages used by a JSP page. This rule is slightly altered if the class is only referenced by
useBeanelements. In these cases, you must only import the class if the class is in the unnamed package. For example, in What Is a JSP Page? , the pageindex.jspimports theMyLocalesclass. However, in the Duke's Bookstore example, all classes are contained in packages and thus are not explicitly imported.
The following element creates an instance of
Currencyif none exists, stores it as an attribute of thesessionobject, and makes the bean available throughout the session by the identifiercurrency:Setting JavaBeans Component Properties
There are two ways to set JavaBeans component properties in a JSP page: with the
jsp:setPropertyelement or with a scriptletThe syntax of the
jsp:setPropertyelement depends on the source of the property value. Table 4-3 summarizes the various ways to set a property of a JavaBeans component using thejsp:setPropertyelement.
A property set from a constant string or request parameter must have a type listed in Table 4-4. Since both a constant and request parameter are strings, the Web container automatically converts the value to the property's type; the conversion applied is shown in the table.
Stringvalues can be used to assign values to a property that has aPropertyEditorclass. When that is the case, thesetAsText(String)method is used. A conversion failure arises if the method throws anIllegalArgumentException. The value assigned to an indexed property must be an array, and the rules just described apply to the elements.
You would use a runtime expression to set the value of a property whose type is a compound Java programming language type. Recall from Expressions that a JSP expression is used to insert the value of a scripting language expression, converted into a String, into the stream returned to the client. When used within a
setPropertyelement, an expression simply returns its value; no automatic conversion is performed. As a consequence, the type returned from an expression must match or be castable to the type of the property.The Duke's Bookstore application demonstrates how to use the
setPropertyelement and a scriptlet to set the current book for the database helper bean. For example,bookstore3/bookdetails.jspuses the form:whereas
bookstore2/bookdetails.jspuses the form:The following fragments from the page
bookstore3/showcart.jspillustrate how to initialize a currency bean with aLocaleobject and amount determined by evaluating request-time expressions. Because the first initialization is nested in auseBeanelement, it is only executed when the bean is created.<jsp:useBean id="currency" class="util.Currency" scope="session"> <jsp:setProperty name="currency" property="locale" value="<%= request.getLocale() %>"/> </jsp:useBean> <jsp:setProperty name="currency" property="amount" value="<%=cart.getTotal()%>"/>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 out object, you must use a scriptlet:
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 formwhereas
bookstore2/showcart.jspuses the form: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: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/showcart.jspreplaces the scriptlet with the following custom tags:<bean:define id="num" name="cart" property="numberOfItems" /> <logic:greaterThan name="num" value="0" >Figure 4-4 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.
![]()
|
FAQ
History |
|
Search
Feedback |
All of the material in The J2EE Tutorial for the Sun ONE Platform is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.