The JSP Files (part 7): Bugs, Beans And Banks - Bean Bag (
Page 6 of 7 )
One of the most
compelling things about JSP, from a development point of view, is that it allows
for the easy integration of existing JavaBeans into JSP scripts (for those of
you not in the loop, JavaBeans is object-oriented technology which allows
developers to build reusable Java components or applications). The advantages of
this are obvious: an organization which has already made an investment in
JavaBeans technology can leverage off it to quickly reuse existing code modules,
at minimal time and cost.
We're not going to get into the nitty-gritty of
building a JavaBean here - there are innumerable tutorials out there on the
topic, including a good one from Sun Microsystems at
http://java.sun.com/docs/books/tutorial/javabeans/.
Instead, we're simply going to touch briefly on the JSP constructs which allow
you to import a Bean into your JSP script, set Bean properties and access Bean
methods.
JavaBeans are brought into a JSP script by means of the
action, which creates an instance of the Bean and identifies the
scope of its activities.
The following code snippet creates an instance
of the Bean "iceCream", identifies it with the unique ID "vanilla" and defines
its scope to be limited to the "page".
<jsp:useBean id="vanilla" scope="page" class="iceCream">
</jsp:useBean>
The "scope" attribute above defines the extent of the
Bean's influence. For example, "scope=page" implies that the instance will
remain active for the current page, while "scope=session" indicates that the
instance will remain available throughout the session.{mospagebreak title=Taking
It To The Bank} Closely related to <jsp:useBean> is
<jsp:setProperty>, typically used to set Bean properties; these properties
may be set explicitly, or on the basis of parameters available in the Request
object (you remember this, don't you?)
The following code snippet uses
the <jsp:setProperty> action to assign the value "7683" to the Bean
property "accountBalance". Note that the <jsp:setProperty> action
references an instance of a previously-defined Bean, named "account"
<jsp:useBean id="account" scope="page" class="Bank">
<jsp:setProperty name="account" property="accountBalance" value="7683" />
</jsp:useBean>
If you'd like to set instance properties on the basis of
data in the Request object - say, form values - you could use
<jsp:setProperty name="account" property="*" />
and JSP would automatically iterate through the Request
object, match parameter names with available Bean properties, and assign values
appropriately.