Java 防SQL注入过滤器(拦截器)代码

原文出自:https://blog.csdn.net/seesun2012

前言

浅谈SQL注入:
       所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令,达到一定的非法用途。


解决办法

1、配置WEB-INF/web.xml

<web-app>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
	
	<!-- 防SQL注入过滤 -->
	<filter>  
        <filter-name>SqlInjectFilter</filter-name>  
        <filter-class>com.seesun2012.web.core.filter.SqlInjectFilter</filter-class>  
		<!-- 过滤前台传入的参数,可手动添加或删减,以“|”分割 -->
		<init-param>
			<param-name>sqlInjectStrList</param-name>
			<param-value>'|or|and|;|-|--|+|,|like|//|/|*|%|#</param-value>
		</init-param>
    </filter>
    <filter-mapping>  
        <filter-name>SqlInjectFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
	</filter-mapping>
	
</web-app>

2、过滤器SqlInjectFilter.java类

package com.seesun2012.web.core.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * SQL注入过滤器
 * @author CSDN:seesun2012
 * @version 0.0.1-SNAPSHOT
 * @Date 2018-01-14
 */
public class SqlInjectFilter implements Filter{
	
	public FilterConfig config;

	@Override
	public void destroy() {
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httprequest = (HttpServletRequest) request;
		// 获得所有请求参数名
		Enumeration<?> params = httprequest.getParameterNames();
		String sql = "";
		while (params.hasMoreElements()) {
			// 得到参数名
			String name = params.nextElement().toString();
			// 得到参数对应值
			String[] value = httprequest.getParameterValues(name);
			for (int i = 0; i < value.length; i++) {
				sql = sql + value[i];
			}
		}
		// 过滤掉的SQL关键字,可以手动添加
		String sqlInjectStrList = config.getInitParameter("sqlInjectStrList");
		if (sqlValidate(sql, sqlInjectStrList)) {	
			throw new IOException("请输入有效字符");
			// 重定向或跳转,略...
		} else {
			chain.doFilter(request, response);
		}
	}
	      
	// 校验SQL
	protected static boolean sqlValidate(String str, String sqlInjectStrList) {
		// 统一转为小写
		str = str.toLowerCase();
		// 转换为数组
		String[] badStrs = sqlInjectStrList.split("\\|");
		for (int i = 0; i < badStrs.length; i++) {
			// 检索
			if (str.indexOf(badStrs[i]) >= 0) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
	}

}


备注

posted @ 2018-06-22 18:04  seesun2012  阅读(2053)  评论(0编辑  收藏  举报