Java Reference
In-Depth Information
The syntax looks like this:
<jsp:useBean id="myvar" class="net.multitool.servlet.AccountBean" />
which will create a variable called
myvar
as an instance of the
AccountBean
class found in the
net.multitool.servlet
package. Think of this as:
<%! import net.multitool.servlet.AccountBean; %>
<% AccountBean myval = new AccountBean(); %>
So can
AccountBean
be any class? Well, sort of. It can be any class that
you want, as long as it is a bean. It doesn't have to end in “
Bean
”, but it does
have to be a class which has:
• A null constructor (you may have noticed there is no syntax to support
arguments to the constructor on the
useBean
statement).
• No public instance variables.
• Getters and setters for instance variables.
• Getters and setters named according to a standard:
getTotal()
or
isTotal()
and
setTotal()
for a variable called
total
(
isTotal()
would be used if we had a boolean getter, that is, if the getter returned a
boolean
; otherwise it would expect
getTotal()
as the getter's name).
Otherwise, its a normal class. These restrictions mean that you can call the
class a “JavaBean” or just “bean,” and there is additional JSP syntax to manipu-
late the class. Specifically:
<jsp:getProperty name="myvar" property="total" />
will do, in effect, the following:
<%= myvar.getTotal() %>
or
<% out.print(myvar.getTotal()); %>
Similarly, we can set a value in the JSP with this syntax:
<jsp:setProperty name="myvar" property="total" value="1234" />