Java Reference
In-Depth Information
dataSource =
catch (NamingException namEx)
This avoids incurring the overhead of JNDI operations being generated for every
HTTP request. In the doGet/doPost method, a database connection can then be
established via method getConnection . For example:
connection = dataSource.getConnection();
(Assuming here, of course, that connection is a pre-declared Connection
SQL statements can then be executed and results processed exactly as they
would have been if the DriverManager class had been used to establish the
However , this will mean that HTML presentation code and database access
code are intermingled in the servlet, which is not a good idea from a design point of
view. It is better to make use of a separate Data Access Object (DAO) to establish
the connection. The creation and use of such objects will be described in the next
Data Access Objects
These encapsulate access to databases so that the data manipulation code can be
separated from the business logic and data presentation code. A DAO is written as
a JavaBean. Though JavaBeans will not be covered formally until a later chapter, all
that need be said right now is that a JavaBean is an ordinary Java class fi le with the
following characteristics:
it is unlikely to have a main method;
it must be in a named package.
The DAO includes a constructor that contains the context-setting and connection
code, along with any other methods required to access and/or manipulate the data
source. Since servlets associated with a particular Web application are contained
within <CATALINA_HOME>\webapps\<WebAppName>\WEB-INF\classes and
the DAO must be in a named package easily accessible to the servlet that will use it,
the DAO will be stored within a sub-folder of classes that has the same name as
its package.
Search WWH ::

Custom Search