struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From J Aaron Farr <jaaronf...@yahoo.com>
Subject Re: dataSources outside of actionservlet
Date Tue, 17 Dec 2002 18:52:32 GMT
On Tue, 17 Dec 2002 17:45, "Mark" <marklowe@libero.it> 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" <edgar@blue-moose.net> 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-sources>
      <data-source key="myDatabase"
                   type="org.apache.struts.util.GenericDataSource">
          <set-property property="url" value=" ... "/>
          ...
      </data-source>
   </data-sources>

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

   Connection dbCon = null;
   
   ServletContext context = servlet.getServletContext();
   DataSource ds = (DataSource) context.getAttribute("myDatabase");
   
   try{
         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 http://ibatis.com/jpetstore/jpetstore.html

Hope that helps.
jaaron

__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com

--
To unsubscribe, e-mail:   <mailto:struts-user-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:struts-user-help@jakarta.apache.org>


Mime
View raw message