Java Reference
In-Depth Information
FIGURE 12-16
Lines 22 through 41 override the init() method to create a StockTrackerDB
object. The init() method is called by the servlet container exactly once to indi-
cate to a servlet that it is being placed into service. Because the init() method is
called only once when the servlet is loaded, only one StockTrackerDB object is
created. The init() method throws a ServletException if an exception that inter-
feres with the servlet's normal operation occurs.
As shown in lines 28 through 39, the constructor for a StockTrackerDB
object throws two exceptions. These exceptions are caught, generating an error
message and exiting the program, as this indicates an error in establishing the
database connection. In each case, the printStackTrace() method for the excep-
tion is called to display a stack trace on the console. A stack trace is a list of
methods, called leading, to the exception and typically is seen when an exception
is not handled. After displaying the stack trace, the program exits by calling the
System.exit() method and passing a value of 1. Passing a nonzero value indicates
that the program exited abnormally.
Likewise, when the servlet no longer is needed, the connection to the data-
base should be closed. Lines 43 through 68 override the destroy() method, call-
ing the close() method of the StockTrackerDB object to close the connection
(line 47). The close() method, like the init() method, throws three exceptions
that are caught, producing a stack trace and then exiting.
 
Search WWH ::




Custom Search