SERVLET.DSLV
Reuse datasources for JDBC connections
Description
This rule flags code that should reuse datasources for JDBC connections, but does not.
A javax.sql.DataSource is obtained from WebSphere Application Server through a JNDI naming lookup. Avoid the overhead of acquiring a javax.sql.DataSource for each SQL access. This is an expensive operation that will severely impact the performance and scalability of the application.
Example
package SERVLET;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
public class DSLV extends HttpServlet {
public void doGet () throws ServletException {
DataSource ds = null; // violation
try {
java.util.Hashtable env = new java.util.Hashtable ();
env.put (Context.INITIAL_CONTEXT_FACTORY, "jndi.
CNInitialContext");
Context ctx = new InitialContext (env);
ds = (DataSource)ctx.lookup ("jdbc/SAMPLE");
ctx.close ();
} catch (Exception e) {
e.printStackTrace ();
}
}
}
Repair
The servlet should acquire the javax.sql.DataSource in the Servlet.init () method (or some other thread-safe method) and maintain it in a common location for reuse.
class Better extends HttpServlet {
// caching the DataSource
private DataSource ds = null;
public void init (ServletConfig config) throws ServletException
{
super.init (config);
Context ctx = null;
try {
java.util.Hashtable env = new java.util.Hashtable ();
env.put (Context.INITIAL_CONTEXT_FACTORY,
"jndi.CNInitialContext");
ctx = new InitialContext (env);
ds = (DataSource)ctx.lookup ("jdbc/SAMPLE");
ctx.close ();
} catch (Exception e) {
e.printStackTrace ();
}
}
}
Reference
IBM WebSphere Application Server Standard and Advanced Editions, Harvey W. Gunther.
http://www-4.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
|