java 如何防止 JSP 中的 SQL 注入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6272861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:08:47  来源:igfitidea点击:

how to prevent SQL Injection in JSP?

javajspjdbcsql-injectionprepared-statement

提问by Nadjib Mami

Just last week, I was doing some PHP stuff. I worked a little solution to prevent SQL injections. PHP has been always my man, it has readily 3 solutions for use (maybe more). One is to enable "magic queries" using stripslashes()function. Another one (the recommended) is to use 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. 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...).

就在上周,我正在做一些 PHP 的东西。我做了一个小解决方案来防止 SQL 注入。PHP 一直是我的男人,它有 3 个可用的解决方案(也许更多)。一种是使用stripslashes()功能启用“魔术查询” 。另一个(推荐)是使用mysql_real_escape_string()函数。就这么简单,我的问题就解决了。然而,当涉及到 JSP 时,事情似乎并没有那么简单。我搜索并没有找到任何内置函数来去除斜杠或执行此类操作(我相信可以使用基本的 JAVA 函数来实现此类功能,但是......)。

Please help me protect my database. I heard about PreparedStatement, but really can't get my head around it? (I feel the real meaning of newbieness).

请帮助我保护我的数据库。我听说过PreparedStatement,但真的无法理解它吗?(我感受到了新手的真正含义)。

回答by BalusC

Just use PreparedStatementinstead of Statement.

只需使用PreparedStatement代替Statement.

I.e. 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 PreparedStatementalso offers convenient setter methods for other types, such as setInt(), setDate(), setBinaryStream(), etcetera.

PreparedStatement还提供了其他类型的方便的设置方法,如setInt()setDate()setBinaryStream(),等等。

Please note that this issue is unrelated to JSP. It's related to Java in general. Writing raw Java code in a JSP class is also considered a poor practice. 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. You can then import/use this DAO class in a servlet class.

请注意,此问题与 JSP 无关。它一般与Java有关。在 JSP 类中编写原始 Java 代码也被认为是一种糟糕的做法。最佳实践是创建一个独立的类,该类在特定表上执行所有数据库交互任务,也称为 DAO(数据访问对象)类。然后您可以在 servlet 类中导入/使用这个 DAO 类。

See also:

也可以看看: