On Wed, 25 Jul 2001, Bud Gibson wrote:
> This looks interesting, but I am not sure how I would use it.
>
> Would the strategy be to set up an action to run when the application is
> loaded? Would the action then obtain a reference to the data source and
> stow it in some repository using JNDI for use by the persistenc layer?
>
> That is the solution we think will work. Is this different from that?
>
> Thanks,
> Bud
>
> >DataSource can be obtained either Deployment descriptor as
> >"java:comp/jdbc/MyDataSource"
> >(associate a Jndi name to the Datasource
> >)
> >
>
>
J2EE-based application servers (and some servlet containers, like Tomcat
4.0) support exactly this approach (JNDI-based access to data sources).
The idea is that you identify (in your web.xml file) a logical name for
the database connection pool you want:
<resource-ref>
<description>My Database</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Somewhere in the administration tools for your server, the system
administrator can set up a connection between this logical name and a
"real" database -- typically, you can set up parameters similar to what
are in the Struts <data-source> element.
Now, in a servlet or a class called by your servlet, you can access the
connection pool like this:
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.sql.DataSource;
...
InitialContext ic = new InitialContext();
DataSource ds =
(DataSource) ic.lookup("java:comp/env/jdbc/MyDataSource");
Connection conn = ds.getConnection();
... use this connection ...
conn.close(); // Returns connection to the pool
As you can see, there's no need for any references to the servlet layer at
all -- this works because the naming context is set up correctly by the
container.
Craig McClanahan