my dog learned polymorphism
The moose likes Java in General and the fly likes DB Connections and Exception Handling in Web Application Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "DB Connections and Exception Handling in Web Application" Watch "DB Connections and Exception Handling in Web Application" New topic

DB Connections and Exception Handling in Web Application

Sahil Sharma
Ranch Hand

Joined: Aug 27, 2003
Posts: 152

I would like to know in a simple web application built using Struts and DAO. How one should do the exception handling and database connections. Should all the DAO class create their own connections and close them or is it better to have a seperate class to handle this.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

In my opinion it's better to configure a connection pool in the application server, rather than making your own connections in any of the applications.
Ganesh Gowtham
Ranch Hand

Joined: Mar 30, 2005
Posts: 225

HI Sahil ,

Why wont you try Spring Framework which does all low level job like opening and closing the db connections and
infact it has api which are wrapped over the core JDBC concepts .

Thanks, Ganesh Gowtham
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

Using a connection pool that's managed by the container is really the only good way to deal with database connections in a web application. Opening a database connection is a relatively slow and heavy operation. Your webapp will become very slow if you open a new connection for each request when the app needs to use the database. It would also make your webapp unable to scale up to large numbers of users, because databases can normally handle only a limited number of connections at a time. A connection pool manages all this for you.

What you'd normally do is setup a connection pool in your container, and then in your webapp get a javax.sql.DataSource object via JNDI, from which you can get the database connection. Here's a tutorial for how to do that with Tomcat.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: DB Connections and Exception Handling in Web Application
It's not a secret anymore!