Java Reference
In-Depth Information
Obtaining the Data Source Connection
In order to use JNDI, it is necessary to import javax.naming . The name used when
referring to the data source within an application program must be identical to that
used in the <res-ref-name> tag within the Web application's deployment descriptor
(the web.xml fi le). In order to resolve the resource associated with this name, it is
necessary to obtain the JNDI context for the Web application. Getting the context
and resolving the resource requires the three steps shown below.
1. Get a reference to the 'initial context', which is the starting context for performing
naming operations. This is done simply by creating an InitialContext object.
For example:
Context initialContext = new InitialContext();
2. Get a reference to the Java environment variables (the 'Java context') by calling
method lookup on the above InitialContext object, supplying the method with the
string “java:comp/env”. This method will return an Object reference that must
be typecast into a Context reference. For example:
Context context =
3. Call method lookup on the Java Context object returned above, supplying it
with the name of the required database, using the name that was supplied in
the <res-ref- name> tag within the deployment descriptor. This will need to be
typecast into a DataSource reference. For example:
dataSource =
Control code for the particular application will be provided by at least one
servlet. The code above can be placed inside the servlet's init method, as shown
in the example below.
private DataSource dataSource;
public void init(ServletConfi g confi g)
throws ServletException
super.init(confi g);
//Carry out generic initialisation
Context initialContext = new InitialContext();
Context context =
Search WWH ::

Custom Search