Java Reference
In-Depth Information
Fig. 8.11 Page output according to user's preferences (as specifi ed in cookies)
8.10
Accessing a Database via a Servlet
Nowadays, accessing a database over the Internet or an intranet is a very common
requirement. Using JDBC within a servlet allows us to do this. In fact, Sect. 7.11
from the preceding chapter demonstrated how to do this through use of the
DataSource interface, which is the 'preferred method' of accessing a remote data-
base via JDBC. However, the more traditional way of providing this access is to use
the DriverManager class and this is still the method used by many Java database
programmers. It is this approach that will be combined with the use of servlets in the
current section.
The only additional servlet methods required are init and destroy . These are
methods of interface Servlet and are implemented by class HttpServlet . Method
init is called up once at the start of the servlet's execution (to carry out any required
initialisation), while method destroy is called up once at the end of the servlet's
execution (to carry out any required 'clean-up' operations, such as returning any
allocated resources). We must provide an overriding defi nition of init that will
load the JDBC driver and set up a database connection. Note that init should fi rst
make a call to super . We also override destroy by supplying a defi nition that
closes the database connection. Both init and destroy must throw (or handle)
ServletException s, of course.
Search WWH ::




Custom Search