rspec/rules/S2655/java/rule.adoc

59 lines
1.6 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
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) {...}
//...
}
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
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) {...}
//...
}
}
----
2021-04-28 16:49:39 +02:00
== See
* https://cwe.mitre.org/data/definitions/245.html[MITRE, CWE-245] - J2EE Bad Practices: Direct Management of Connections
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]