Java secure coding¶
Java services need explicit boundaries between request data, database commands and returned HTML. This guide uses JDBC in a servlet or Spring application. The same principle applies when a framework offers a raw-query escape hatch: the query structure must not come from an untrusted value.
Use a prepared statement¶
Assume connection is an open JDBC connection and email is a validated string from the request. Handle checked SQL exceptions through your application's normal error boundary.
Unsafe: concatenate the value into SQL.
String sql = "SELECT id FROM customers WHERE email = '" + email + "'";
try (Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery(sql)) {
// Read only authorized records.
}
Safer: bind it through JDBC.
String sql = "SELECT id FROM customers WHERE email = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, email);
try (ResultSet rows = statement.executeQuery()) {
// Read only authorized records.
}
}
The driver receives the value separately from the statement. An apostrophe remains part of the email value. Try-with-resources closes both the statement and result set even on an error. See Oracle's JDBC prepared statement guide.
Binding does not establish permission to view a matching customer. Apply tenant and ownership constraints before returning records, and use a database account with only the required privileges. Map dynamic identifiers such as sort columns to a small server-defined list; parameter placeholders are for values.
Check the fix¶
Create two fictional records in a disposable database, including o'reilly@example.test. A lookup must return exactly the matching record and leave the other unchanged. Check that missing records return the application's normal empty response and that errors never expose connection strings or stack traces.
Review SQL injection, XXE, LDAP injection and TLS certificate validation. For HTML responses, keep the template engine's output escaping enabled. OWASP's SQL prevention guidance provides additional controls.
Examples teach a specific fix; Java scanner coverage varies by framework, code path and enabled rules. Review any partial or skipped analysis before drawing conclusions.