sql注入

登录时,后台sql语句,是用拼凑写的,

如:String sql = "select count(*) from user where name='" + user +"' and password=''' + pw;

spring的jdbc接口getJdbcTemplate().queryForInt(sql);

当前台,帐号中输入:admin' or '1'='1时,再密码任意输,结果到后台sql就变成:

 

 select count(*) from user where name='admin' or '1'='1' and password='xxx';

这样就会被注入。

 

所以要改一下,sql= "select count(*) from user where name=? and password=?";

getJdbcTemplate().queryForInt(sql, new Object[]{user, pw});

 

 

原因:

public int queryForInt(String sql)
                throws DataAccessException
Description copied from interface: JdbcOperations
Execute a query that results in an int value, given static SQL.

Uses a JDBC Statement, not a PreparedStatement

 

public int queryForInt(String sql,
                       Object[] args)
                throws DataAccessException
Description copied from interface: JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, resulting in an int value.

The query is expected to be a single row/single column query that results in an int value.

防止sql注入,要用jdbc的 PreparedStatement

 

你可能感兴趣的:(sql注入)