Java Reference
In-Depth Information
Figure 18−2. The output of the Query servlet
The code for this example is pretty straightforward. The init() method reads ini-
tialization parameters that specify the JDBC driver to use, the database to connect
to, and the username and password to use when connecting. init() uses this
information to establish a database connection that persists for the lifetime of the
servlet; the connection is closed in the destroy() method. Creating a persistent
connection means you don't have the overhead of establishing and closing a con-
nection for each servlet request. It does assume, however, that the JDBC driver
you use is thread-safe, and it only works if you limit yourself to database queries
and simple updates that do not require transactions. If you need to work with
transactions, you can synchronize the doGet() method to ensure that the servlet
runs only one request at a time. Or, if you have a high-traffic web site, you can
use a technique known as connection pooling to create connections in advance
and distribute them to request threads as needed. This and related techniques are
well explained in Java Servlet Programming .
The doGet() method uses standard JDBC code (see Chapter 17, Database Access
with SQL ) to send a SQL query to the database server and output the results in the
form of an HTML table. (See an HTML reference such as O'Reilly's HTML : The
Definitive Guide , by Chuck Musciano and Bill Kennedy, if you're not familiar with
<table> and related HTML tags.) doGet() also displays the form that allows the
user to enter the SQL query. When the user submits the form, the browser reloads
the servlet, passing the user's SQL query as a request parameter. Including both
form generation and form-processing code in the same servlet is a common and
useful servlet programming technique.
Finally, note that the doGet() method uses a RequestDispatcher() object to
invoke the Counter servlet and include the output of that servlet in its own output.
doGet() uses setAttribute() to specify the counter name as a request attribute.
The Counter servlet contains the corresponding call to getAttribute() .
Search WWH ::




Custom Search