== Why is this an issue?

The JEE standard forbids the direct management of connections in JEE applications. But if that's not reason enough to delegate connection management to the servlet container, consider that the container is both better positioned and better equipped to manage resources not just for a single class, but across classes in an application. Further, mis-managing connections in a JEE class can lead to connection leaks which could compound into a denial of service.


This rule raises an issue for each use of a DriverManager in a servlet class.


=== Noncompliant code example

[source,java]
----
private static final String CONNECT_STRING = "jdbc:mysql://localhost:3306/mysqldb";

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException  {

  Connection conn = null;
  try {
    conn = DriverManager.getConnection(CONNECT_STRING);  // Noncompliant
    // ...
  } catch (SQLException ex) {...}
    //...
  }
}
----


=== Compliant solution

[source,java]
----
private static final String DB_LOOKUP = "jdbc/mainDb";

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException  {

  Connection conn = null;
  try {
    InitialContext ctx = new InitialContext();
    DataSource datasource = (DataSource) ctx.lookup(DB_LOOKUP);
    conn = datasource.getConnection();
    // ...
  } catch (SQLException ex) {...}
    //...
  }
}
----


== Resources

* https://cwe.mitre.org/data/definitions/245[MITRE, CWE-245] - J2EE Bad Practices: Direct Management of Connections


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Use a JNDI-supplied DataSource instead.


'''
== Comments And Links
(visible only on this page)

=== on 27 Feb 2015, 20:14:42 Ann Campbell wrote:
\[~nicolas.peru] I've written this rule more narrowly than the CWE example shows: i.e. I've written that we'll raise an issue when a servlet class uses ``++DriverManager++``, but the CWE example shows a delegate class being used to interact with ``++DriverManager++``. 


I'm guessing that detecting this case as well will take CFG?

=== on 13 Apr 2015, 14:48:39 Nicolas Peru wrote:
\[~ann.campbell.2]just to be sure of my understanding : you are talking about a servlet using a class of the project using ``++DriverManager++`` ? 


This is not related to CFG, but more to an analysis of what is in the project or not. We can find way to do it but it is not easy given the current implementation of things right now to know if a class is defined in the project or not. 


I would probably stick to this simpler implementation as a first step.

=== on 20 Jul 2015, 07:37:26 Ann Campbell wrote:
Tagged java-top by Ann

endif::env-github,rspecator-view[]
