简体   繁体   中英

how to prevent SQL Injection in JSP?

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

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

Just use PreparedStatement instead ofStatement .

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.

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.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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