简体   繁体   English

如何防止 JSP 中的 SQL 注入?

[英]how to prevent SQL Injection in JSP?

Just last week, I was doing some PHP stuff.就在上周,我正在做一些 PHP 的事情。 I worked a little solution to prevent SQL injections.我做了一个小解决方案来防止 SQL 注射。 PHP has been always my man, it has readily 3 solutions for use (maybe more). PHP 一直是我的男人,它有 3 种解决方案可供使用(也许更多)。 One is to enable "magic queries" using stripslashes() function.一种是使用stripslashes() function 启用“魔术查询”。 Another one (the recommended) is to use mysql_real_escape_string() function.另一种(推荐)是使用mysql_real_escape_string() function。 That simple and my problem is solved.这么简单,我的问题就解决了。 However, things don't seem to be that simple when it comes to JSP.然而,当谈到 JSP 时,事情似乎并不那么简单。 I searched and didn't find any built-in function to strip slashes or do those sort of things (I believe such functionality can be implemented using basic JAVA functions but...).我搜索并没有找到任何内置的 function 来去除斜线或做这些事情(我相信这样的功能可以使用基本的 JAVA 函数来实现,但是......)。

Please help me protect my database.请帮助我保护我的数据库。 I heard about PreparedStatement , but really can't get my head around it?我听说过PreparedStatement ,但真的无法理解它吗? (I feel the real meaning of newbieness). (我感受到了新手的真正含义)。

Just use PreparedStatement instead ofStatement .只需使用PreparedStatement而不是Statement

Ie use即使用

String sql = "INSERT INTO tbl (col1, col2, col3) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, col1);
preparedStatement.setString(2, col2);
preparedStatement.setString(3, col3);
preparedStatement.executeUpdate();

instead of代替

String sql = "INSERT INTO tbl (col1, col2, col3) VALUES ('" + col1 + "', '" + col2 + "', '" + col3 + "')";
statement = connection.createStatement();
statement.executeUpdate(sql);

The PreparedStatement also offers convenient setter methods for other types, such as setInt() , setDate() , setBinaryStream() , etcetera. PreparedStatement还为其他类型提供了方便的 setter 方法,例如setInt()setDate()setBinaryStream()等。

Please note that this issue is unrelated to JSP.请注意,此问题与 JSP 无关。 It's related to Java in general.一般与Java有关。 Writing raw Java code in a JSP class is also considered a poor practice .在 JSP class 中编写原始 Java 代码也被认为是一种不好的做法 Best practice is to create a standalone class which does all the DB interaction tasks on a particular table, which is also called a DAO (Data Access Object) class.最佳实践是创建一个独立的 class,它在特定表上执行所有 DB 交互任务,该表也称为 DAO(数据访问对象)class。 You can then import/use this DAO class in a servlet class.然后,您可以在 servlet class 中导入/使用此 DAO class。

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM