Java Reference
In-Depth Information
As shown in line 18 in Figure 12-15 on the previous page, the WebStocks
class extends the HttpServlet class, which is not available in the standard SDK.
The HttpServlet class instead is provided as part of a package with the servlet
container, Tomcat, which is used in this project. The package is provided in a
Java Archive (JAR) file, named servlet-api.jar, in the C:\Program Files\Apache
Software Foundation\Tomcat 5.5\common\lib folder. Recall from Chapter 8 that
a Java Archive (JAR) file is a compressed archive file, used to contain related files
in a package. It is common for packages to be distributed in this format, and Java
can access the classes directly from the JAR file without extracting them. To use
the HttpServlet class, the import statements using the javax packages must be
included.
Overriding Servlet init() and destroy() Methods
The WebStocks servlet uses the StockTrackerDB class to access the database,
as did the StockTracker application. When a StockTrackerDB object is created, it
establishes a connection with the database. Establishing a database connection is
a relatively slow process, which you do not want to repeat with each new request.
In a production environment, particularly one using a multi-tiered architecture
where the database is located on a server separate from the application, connec-
tion pooling frequently is used. Connection pooling is a technique for creating
multiple database connections and then assigning them in a round-robin fashion
to servlet threads. In this chapter, connection pooling is not used; instead, only
one connection is used for simplicity. Thus, you will override the init() and
destroy() methods of the StockTrackerDB class to ensure the database connec-
tion is maintained for the life of the servlet.
Figure 12-16 displays lines 20 through 69 of the WebStocks servlet code. Line
20 establishes the variable, db, for the StockTrackerDB object. Recall that, because
servlets are multithreaded, instance variables such as db are shared among multi-
ple threads. Therefore, only one StockTrackerDB object needs to be created.
FIGURE 12-16
 
Search WWH ::




Custom Search