Java防止SQL注入的方法

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

01import java.io.IOException;
02import java.util.Iterator;
03import javax.servlet.Filter;
04import javax.servlet.FilterChain;
05import javax.servlet.FilterConfig;
06import javax.servlet.ServletException;
07import javax.servlet.ServletRequest;
08import javax.servlet.ServletResponse;
09import javax.servlet.http.HttpServletRequest;
10import javax.servlet.http.HttpServletResponse;
11/**
12* 通过Filter过滤器来防SQL注入攻击
13*
14*/
15public class SQLFilter implements Filter {
16private String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,";
17protected FilterConfig filterConfig = null;
18/**
19* Should a character encoding specified by the client be ignored?
20*/
21protected boolean ignore = true;
22public void init(FilterConfig config) throws ServletException {
23this.filterConfig = config;
24this.inj_str = filterConfig.getInitParameter("keywords");
25}
26public void doFilter(ServletRequest request, ServletResponse response,
27FilterChain chain) throws IOException, ServletException {
28HttpServletRequest req = (HttpServletRequest)request;
29HttpServletResponse res = (HttpServletResponse)response;
30Iterator values = req.getParameterMap().values().iterator();//获取所有的表单参数
31while(values.hasNext()){
32String[] value = (String[])values.next();
33for(int i = 0;i < value.length;i++){
34if(sql_inj(value[i])){
35//TODO这里发现sql注入代码的业务逻辑代码
36return;
37}
38}
39}
40chain.doFilter(request, response);
41}
42public boolean sql_inj(String str)
43{
44String[] inj_stra=inj_str.split("\\|");
45for (int i=0 ; i < inj_stra.length ; i++ )
46{
47if (str.indexOf(" "+inj_stra[i]+" ")>=0)
48{
49return true;
50}
51}
52return false;
53}
54}

也可以单独在需要防范SQL注入的JavaBean的字段上过滤:

1/**
2* 防止sql注入
3*
4* @param sql
5* @return
6*/
7public static String TransactSQLInjection(String sql) {
8return sql.replaceAll(".*([';]+|(--)+).*", " ");
9}

相关推荐