File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Database Connection in Servlet

 
Timotius Pamungkas
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi...

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?

Thanks
 
chnaresh Cheedella
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 135
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic