Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 430
Nadjib Mami Avatar asked Jun 07 '11 23:06

Nadjib Mami


1 Answers

Just use PreparedStatement instead of 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 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:

  • Java Tutorials - JDBC Tutorial - PreparedStatement
  • Difference between Statement and PreparedStatement
  • how to send a ResultSet object in jsp back to html (javascript)?
like image 65
BalusC Avatar answered Sep 23 '22 00:09

BalusC