Hi all. I'm new to this, so bear with me! I have a web application which is for installing on multiple other users' servers (running Tomcat). I want to use connection pooling, but I don't want users to have to set up data source information in their Tomcat configuration files.
So, I was going to use something like this (found on usenet):
However, I'm not sure how best to deploy this. I don't want to create a new datasource everytime I need to connect to a database, do I? Should I rewrite this class as a servlet, and run it on my webapp's startup, then use the same datasource in all the jsp pages in my application?
How about closing the datasource? Do I need to do that or will it happen automatically when I return all the datasource's connections?
Hi Jeanne, So make the datasource a static variable, and just instantiate it from the first jsp page of my webapp? No need to make the class a servlet?
Should I create it using a Singleton pattern, or am I getting over-complicated?
This is a newbie Java scope question, rather than a JDBC question, but does that mean that if one user is accessing the webapp, and the datasource is instantiated, then if a second user accesses it, the same datasource instance will be used?
Thanks! Mike [ August 10, 2005: Message edited by: Mikey Kelly ]
Joined: Aug 09, 2005
This is what I tried - seems to be working OK:
then in the jsp pages:
Seems reasonable? Thanks, M [ August 10, 2005: Message edited by: Mikey Kelly ]
Mikey, Definitely reasonable! And yes, if a second user comes along, he/she will use the same DataSource. This is what you want. The DataSource has multiple connections in the pool and will handle not giving out more than one at a time.
Note that it is considered a best practice to avoid having database code in the JSP. Instead, you have the servlet (or a class that it calls) do the database stuff and put the result in a request attribute for the JSP to retrieve. Just something to keep in mind as you learn more.
Joined: Aug 09, 2005
Thanks Jeanne. Just one more clarification.
Should I be using a singleton pattern in DatabaseUtils?
Every time I call DatabaseUtils.getDataSource(), will the getDataSource() function go through the procedure of making a new BasicDataSource, etc. before returning the static DataSource? Or will it only go through the DataSource creation process if the DataSource doesn't exist?
Also, it would be really useful to see any examples of moving database queries out of the JSP page if you know of any.
Thanks for your help! M [ August 11, 2005: Message edited by: Mikey Kelly ]