两种方式来防止sql注入的问题。

本文详细介绍了如何通过使用PreparedStatement、过滤器、HQL等方法在Java和HQL环境中防止SQL注入攻击,确保应用程序的安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1>JAVA防SQl注入 ,最简单的办法是杜绝SQL拼接,SQL注入攻击能得逞是因为在原有SQL语句中加入了新的逻辑,如果使用PreparedStatement 来代替Statement来 执行SQL语句,其后只是输入参数,SQL注入攻击手段将无效,这是因为PreparedStatement不允许在不同的插入时间改变查询的逻辑结构, 大部分的SQL注入已经挡住了, 在WEB层我们可以过滤用户的输入来防止SQL注入 比如用Filter来过滤全局的表单参数

2>HQL防止sql注入,利用set方法给sql中的?赋值。

1 通过Filter过滤器来防SQL注入攻击 

 public class SQLFilter implements Filter { 

 private String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,"; 

 protected FilterConfig filterConfig = null; 

 /** 

 * Should a character encoding specified by the client be ignored? 

*/

 protected boolean ignore = true; 

 public void init(FilterConfig config) throws ServletException { 

 this.filterConfig = config; 

 this.inj_str = filterConfig.getInitParameter("keywords"); 

 } 

 public void doFilter(ServletRequest request, ServletResponse response, 

 FilterChain chain) throws IOException, ServletException { 

 HttpServletRequest req = (HttpServletRequest)request; 

 HttpServletResponse res = (HttpServletResponse)response; 

 Iterator values = req.getParameterMap().values().iterator();//获取所有的表单参数 

 while(values.hasNext()){ 

String[] value = (String[])values.next(); 

 for(int i = 0;i < value.length;i++){ 

 if(sql_inj(value[i])){ 

 //TODO这里发现sql注入代码的业务逻辑代码 

return; 

 } 

 } 

chain.doFilter(request, response); 

 } 

 public boolean sql_inj(String str) 

 { 

 String[] inj_stra=inj_str.split("\\|"); 

 for (int i=0 ; i < inj_stra.length ; i++ ) 

 { 

if (str.indexOf(" "+inj_stra[i]+" ")>=0) 

 return true; 

 } 

 } 

 return false; 

}
2单独在需要防范SQL注入的JavaBean的字段上过滤:

public static String TransactSQLInjection(String sql) {
return sql.replaceAll(".*([';]+|(--)+).*"," ");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值