Java防SQL注入,最简单的办法是杜绝SQL拼接,SQL注入攻击能得逞是因为在原有SQL语句中加入了新的逻辑,如果使用PreparedStatement来代替Statement来执行SQL语句,其后只是输入参数,SQL注入攻击手段将无效,这是因为PreparedStatement不允许在不同的插入时间改变查询的逻辑结构,大部分的SQL注入已经挡住了,在WEB层我们可以过滤用户的输入来防止SQL注入比如用Filter来过滤全局的表单参数。
importjava.io.IOException;
importjava.util.Iterator;
importjavax.servlet.Filter;
importjavax.servlet.FilterChain;
importjavax.servlet.FilterConfig;
importjavax.servlet.ServletException;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*通过Filter过滤器来防SQL注入攻击
*
*/
publicclassSQLFilterimplementsFilter{
privateStringinj_str=""|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
protectedFilterConfigfilterConfig=null;
/**
*Shouldacharacterencodingspecifiedbytheclientbeignored?
*/
protectedbooleanignore=true;
publicvoidinit(FilterConfigconfig)throwsServletException{
this.filterConfig=config;
this.inj_str=filterConfig.getInitParameter("keywords");
}
publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
FilterChainchain)throwsIOException,ServletException{
HttpServletRequestreq=(HttpServletRequest)request;
HttpServletResponseres=(HttpServletResponse)response;
Iteratorvalues=req.getParameterMap().values().iterator();//获取所有的表单参数
while(values.hasNext()){
String[]value=(String[])values.next();
for(inti=0;i<value.length;i++){
if(sql_inj(value[i])){
//TODO这里发现sql注入代码的业务逻辑代码
return;
}
}
}
chain.doFilter(request,response);
}
publicbooleansql_inj(Stringstr)
{
String[]inj_stra=inj_str.split("\\|");
for(inti=0;i<inj_stra.length;i++)
{
if(str.indexOf(""+inj_stra[i]+"")>=0)
{
returntrue;
}
}
returnfalse;
}
}
也可以单独在需要防范SQL注入的JavaBean的字段上过滤:
/**
*防止sql注入
*
*@paramsql
*@return
*/
publicstaticStringTransactSQLInjection(Stringsql){
returnsql.replaceAll(".*([";]+|(--)+).*","");
}