如何防止使用JPA和Hibernate进行SQL注入?
问题描述:
我正在使用休眠模式开发应用程序.当我尝试创建登录页面时,出现Sql注入问题. 我有以下代码:
I am developing an application using hibernate. When I try to create a Login page, The problem of Sql Injection arises. I have the following code:
@Component
@Transactional(propagation = Propagation.SUPPORTS)
public class LoginInfoDAOImpl implements LoginInfoDAO{
@Autowired
private SessionFactory sessionFactory;
@Override
public LoginInfo getLoginInfo(String userName,String password){
List<LoginInfo> loginList = sessionFactory.getCurrentSession().createQuery("from LoginInfo where userName='"+userName+"' and password='"+password+"'").list();
if(loginList!=null )
return loginList.get(0);
else return null;
}
}
在这种情况下如何防止Sql注入?loginInfo表的创建表语法如下:
How will i prevent Sql Injection in this scenario ?The create table syntax of loginInfo table is as follows:
create table login_info
(user_name varchar(16) not null primary key,
pass_word varchar(16) not null);
答
Query q = sessionFactory.getCurrentSession().createQuery("from LoginInfo where userName = :name");
q.setParameter("name", userName);
List<LoginInfo> loginList = q.list();
您还有其他选择,请参见以下精美的文章来自mkyong.
You have other options too, see this nice article from mkyong.