This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Database Connection in Servlet

 
Timotius Pamungkas
Greenhorn
Posts: 28
  • 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
  • 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
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic