Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do i get a connection object in a java class ; am using struts datasource

 
Anil Verghese
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have configured my appln to use the struts application. I have some Java utility classes how do i get the connections over there.
Is using struts datasource efficient way to do the connection pooling if not can any one suggest a better way to do this

Anil
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anil Verghese:
Is using struts datasource efficient way to do the connection pooling if not can any one suggest a better way to do this

No, it is not, nor does it facilitate the Model/View/Controller model that Struts is trying to promote. It is mainly for this reason that the Struts Datasource utility has been removed from later versions.

The best practice for using data in J2EE applications is to set up the data source using application server utilities that place a reference to it in the Java Naming and Directory Interface (JNDI). In your application code, you would then retrieve this reference with a JNDI lookup.

The preferred method for setting up a JNDI datasource is different for each application server. Look in the documentation for your application server under a heading such as "JNDI DataSource".

For more information on this topic, read chapter 31 of the Sun J2EE Tutorial
 
Anil Verghese
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the reply. What are the advantages if I create a datasource and use JNDI.
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main advantage is that it solves the very problem you started this thread about: Accessibility of the DataSource from any class. The Struts DataSource utility stores the DataSource in Application Context (i.e. the ServletContext object). From a normal POJO class, you don't normally have access to the Application Context, so you really can't get the DataSource.

If you use a JNDI DataSource, you can access it from any POJO that is running inside the Java EE container.

This makes it so you can provide proper separation of layers between Model and Controller. It's really the domain of model objects to access the database, not the controller. So, why make it so the only way to access a DataSource is in a controller object such as an action class? I believe this is the main reason why the Struts DataSource was dropped completely from later releases.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic