Hello,
I am running Tomcat struts. I am beginning a new project using the struts
technologies and have a question in regards to handling connections.
First off, just to give you some background, older projects I worked on had a
singleton class that handed me database connections. So when I needed a
connection, I would just ask for a connection from a static class.
Now that I am starting into my struts project, I am beginning to wonder how the
best practice would be to handle connections. In tomcat I configured a
<ResourceParams name="jdbc/JNDITest" object to configure the data source.
Now in my java class files, I am finding myself doing the following:
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/JNDITest");
Connection con = ds.getConnection();
PreparedStatement select = con.prepareStatement("Select * from exchange");
ResultSet rs = select.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("rate"));
}
rs.close();
select.close();
con.close();
The problem is, this seems a lot messier than using a singleton and getting
handed connections. I may be mistaken, and if so I apologize, but it just seems
like a lot of duplication of code for the above.
Also I am using some taglibs in which I need to connect to the database.
Could anyone give me some suggestions, in "best" practices using these
technologies.
Thanks for your time,
Sincerely
Scott