如何防止JSP中的SQL注入? [英] how to prevent SQL Injection in JSP?

查看:118
本文介绍了如何防止JSP中的SQL注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就在上周,我正在做一些PHP的东西。我使用了一点解决方案来防止SQL注入。 PHP一直是我的人,它有3个解决方案可供使用(可能更多)。一种是使用 stripslashes()函数启用魔术查询。另一个(推荐)是使用 mysql_real_escape_string()函数。
这很简单,我的问题就解决了。但是,当谈到JSP时,事情似乎并不那么简单。我搜索并没有找到任何内置函数去除斜线或做那些事情(我相信这样的功能可以使用基本的JAVA函数实现但是......)。

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...).

请帮我保护我的数据库。我听说过 PreparedStatement ,但真的无法理解它? (我觉得新手的真正含义)。

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 而不是 声明

Just use PreparedStatement instead of Statement.

即使用

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();

而不是

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

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

The PreparedStatement also offers convenient setter methods for other types, such as setInt(), setDate(), setBinaryStream(), etcetera.

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

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.

  • Java Tutorials - JDBC Tutorial - PreparedStatement
  • Difference between Statement and PreparedStatement
  • how to send a ResultSet object in jsp back to html (javascript)?

这篇关于如何防止JSP中的SQL注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆