Java Reference
In-Depth Information
For example:
<jsp:useBean id="myAccount" class="bank.Account"
scope="session" />
Recall that Tomcat has a folder called classes. For each bean that we wish to use
with a JSP, we should create a sub-folder of
classes
that has the same name as the
package that is to hold the bean. For instance, in the above example, directory
bank
holds a bean called
Account
(within package
bank
) and directory
bank
is placed
inside
classes
. Once a bean has been placed inside a JSP, the 'get' and 'set' methods
of the bean may be used.
There is a great deal of scope for things to go wrong when using JavaBeans from
JSPs, so you should get used to seeing error pages. In addition to this, re-compilation
by the server (necessary after any change to the JSP, of course) is
slow
! Re-loading
of a pre-compiled JSP is fi ne, though. In addition, recall that it is not necessary
to stop and restart the server every time a change is made to a JSP (as it was with
servlet changes in Chap.
8
).
10.6.2
Calling a Bean's Methods Directly
Example
This is a modifi cation of one of our JDBC examples (
JDBCGUI.java
) from Chap.
7
.
It is advisable to specify an error page, of course, since several things can go wrong
when accessing a database that could be remote.
There are several changes that need to be made to the original program, as listed
below.
Remove all references to GUI elements (substantially reducing the code in so
doing).
Remove all exception-handling code (since we shall be using a JSP error page).
Since class
ResultSet
has no constructor and does not implement
Serializable
,
introduce a
Vector
for transferring query results.
Introduce a 'get' method for retrieving the contents of the
Vector
object.
The numeric values retrieved from the database and stored in a
Vector
will need
to be typecast into objects of the type
Integer
and
Float
when the
Vector
is received
by the JSP. Due to auto-unboxing, these values may be assigned directly to variables
of type
int
and
fl oat
.
Here is the code for the bean…
package jdbc;
import java.sql.*;
import java.util.Vector;
public class JDBCBean
Search WWH ::
Custom Search