flawopen.com/SQL 注入/Java
想象一个只接收取件码的窗口。SQL 注入就是有人在输入框里输入了一段特殊指令,导致系统把所有人的快递信息全倒了出来,因为系统根本没验证输入是不是合法数字。
SQL 注入 in Java occurs when unvalidated strings are concatenated into JDBC Statement or HQL/JPQL queries.
In 2005, the Samy XSS worm infected over 1 million user profiles on MySpace in under 20 hours, forcing the platform offline.
Documented historical AppSec case study.// userId comes straight from the request
String query = "SELECT * FROM users "
+ "WHERE id = " + userId;
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
// value is bound, never concatenated
String query = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt =
connection.prepareStatement(query);
stmt.setString(1, userId);
ResultSet rs = stmt.executeQuery();
PreparedStatement precompiles the query structure in the database engine, binding parameter values separately.
#{} uses safe parameterized binding, while ${} performs raw string substitution.
Concatenating HQL queries is just as dangerous as raw SQL. Always use setParameter().
Only if the stored procedure itself uses parameters rather than dynamic EXECUTE strings.
grep -rn "createStatement().*executeQuery(.*+" --include="*.java" .
FindSecBugs plugin in CI to catch SQL_INJECTION_JDBC automatically.Derived queries (@Query) are safe if method parameters are bound with :param or ?1.