struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From J Aaron Farr <>
Subject Re: dataSources outside of actionservlet
Date Tue, 17 Dec 2002 18:52:32 GMT
On Tue, 17 Dec 2002 17:45, "Mark" <> wrote:
>Thanks edgar.. 
>For those folks who are starting out or don't read binary
>Context and InitialContext are part of the javax.naming package....
>So you'll need to 
>import javax.naming.Context;
>import javax.naming.InitialContext;
>The javadocs are less cryptic.. Sometimes is just knowing which ones one has
>to read.. 
>Many thanks again mark
>On 17-12-2002 17:18, "Edgar P. Dollin" <> wrote:
>>           Context env = (Context) new
>> InitialContext().lookup("java:comp/env");
>>           DataSource ds = (DataSource) env.lookup("yourconnection");
>>           conn = ds.getConnection();

Here's another way to do it without using JNDI:

Given a stuts-config.xml file with a datasource like this:

      <data-source key="myDatabase"
          <set-property property="url" value=" ... "/>

You can access a database connection in your Action like this:

   Connection dbCon = null;
   ServletContext context = servlet.getServletContext();
   DataSource ds = (DataSource) context.getAttribute("myDatabase");
         dbCon = ds.getConnection();

Now at this point you want to use a "model" or "business" object that handles
that actual logic.  For example, suppose we have a Product class:

         Product product = new Product();
         List productList = product.getProductList(dbCon);

Or something like that.

This should keep proper MVC design.  If anyone has a good reason why one should
use JNDI rather than the servlet context, I'd like to here it.  (I guess I can
think of a few cases...).

Also, I found the DAO (Data Access Object) pattern implemented in the JPetStore
example helpful in learning how to properly seperate models and actions. 
JPetStore is a Struts implementation of Sun's J2EE PetStore.  It uses its own
database connection pooling, but the DAO stuff is good nonetheless.  JPetStore
can be found at

Hope that helps.

Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.

To unsubscribe, e-mail:   <>
For additional commands, e-mail: <>

View raw message