I hope this question doesn't come across dumb and that it makes sense. I am fairly new to Java and OOP in general.
As I mentioned in a previous post, I am teaching myself servlets and everything that goes with them by "porting" a PHP application to Java. I've got my initial testing servlet working with JDBC connection pooling and I've done it a few different ways, my question is which one is correct when it comes to following the MVC design pattern? Is it ok to have the database connection setup in my controller (servlet) and then passed to my methods (models) or should I have anything database related in the model class?
Here is some code on what I'm working with. I have an application specific web.xml and context.xml files that setup my database listener/connection info. This listener is called via the containers contextInitialized() method where it looks up the datasource and then makes it usable for the rest of the app:
Next, the actual servlet in this setup creates a reference to the datasource in it's init() method, creates an actual connection in it's doGet() method, and then passes that connection to my methods/models so they can connect to the database. Here is the datasource/connection setup in the servlet:
And the code from ModelClass:
This works and everything, but from what I've read regarding MVC, it sounds like I might want to move the database stuff out of the servlet and into my model classes, is that right? The other night I created a DBUtils class that handled everything and then instantiated it in the servlet init() method. I moved all the connection creation stuff outside of the servlet code and into my model code.
So I guess I have a few questions:
- Is the code up above "ok" from a design sense or does the database stuff need to be moved around?
- Is it "ok" to use contextInitialized() to setup my datasource or should I do everything from a database utility class which is instantiated via init()?
- In regards to the previous question, should I even have any database related logic in the servlet init() method or just save it all for the utility class?
I apologize for the long post, but I wanted to use some of the actual code to illustrate what I was doing.