File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Database Connection in Servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Database Connection in Servlet" Watch "Database Connection in Servlet" New topic

Database Connection in Servlet

Timotius Pamungkas

Joined: Feb 26, 2005
Posts: 28

Just wonder, which approach is better?
I have two classes for database connection (standard, non servlet java class) : apache/dbcp-based DBPool and class DBConnection that retrieves and returns connection from pool, execute queries, etc.

Now, when I'm trying to use web app using JSP/servlet, should I recode them into DBPoolServlet (and get usernames, password, driver in it's init() method) and DBConnectionServlet, or just use them as is (non-servlet-class)? What is the cost-benefit?

chnaresh Cheedella

Joined: Nov 01, 2006
Posts: 7
What my suggetion is

Don't put ant database related code in the servlet.
You create one class(DAO ata Access Object) that should be deal with
all database related problems.Then use that class in your servlet whenever you want to interact with database.

That is the best approach.
Eddy Lee Sin Ti
Ranch Hand

Joined: Oct 06, 2005
Posts: 135
Hi, Timotius

The idea of servlet is to extend the capability of the web server to do specific processing based on the action that user specified, in this case can be determined from the servlet path in the url. Database connection is internal to the application and use only by the application components and not to be served to the end user over http, assuming you are using HttpServlet.

Any MVC/Model2 or other architectural guru will tell you to place only the database access code in the model or in the persistence layer, but not to mix them up in the presentation code or business logic components.

And to make some other points of why you shouldn't even think about DBPoolServlet and DBConnectionServlet are that the instances of servlet are managed by the container and you cant be sure which one your code will get.

So, my humble opinion is generally no pros. tons of cons.

Hope this helps. Cheers.

SCJP, SCWCD, SCJWS, IBM 700,IBM 701, IBM 704, IBM 705, CA Clarity Technical<br /> <br /><a href="" target="_blank" rel="nofollow"></a>
I agree. Here's the link:
subject: Database Connection in Servlet
It's not a secret anymore!