java防SQL注入,最简单的办法是杜绝SQL拼接,SQL注入攻击能得逞是因为在原有SQL语句中加入了新的逻辑,如果使用PreparedStatement来代替Statement来执行SQL语句,其后只是输入参数,SQL注入攻击手段将无效,这是因为PreparedStatement不允许在不同的插入时间改变查询的逻辑结构 ,大部分的SQL注入已经挡住了, 在WEB层我们可以过滤用户的输入来防止SQL注入比如用Filter来过滤全局的表单参数
01 | import java.io.IOException; |
02 | import java.util.Iterator; |
03 | import javax.servlet.Filter; |
04 | import javax.servlet.FilterChain; |
05 | import javax.servlet.FilterConfig; |
06 | import javax.servlet.ServletException; |
07 | import javax.servlet.ServletRequest; |
08 | import javax.servlet.ServletResponse; |
09 | import javax.servlet.http.HttpServletRequest; |
10 | import javax.servlet.http.HttpServletResponse; |
15 | public class SQLFilter implements Filter { |
16 | private String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|," ; |
17 | protected FilterConfig filterConfig = null ; |
19 | * Should a character encoding specified by the client be ignored? |
21 | protected boolean ignore = true ; |
22 | public void init(FilterConfig config) throws ServletException { |
23 | this .filterConfig = config; |
24 | this .inj_str = filterConfig.getInitParameter( "keywords" ); |
26 | public void doFilter(ServletRequest request, ServletResponse response, |
27 | FilterChain chain) throws IOException, ServletException { |
28 | HttpServletRequest req = (HttpServletRequest)request; |
29 | HttpServletResponse res = (HttpServletResponse)response; |
30 | Iterator values = req.getParameterMap().values().iterator(); |
31 | while (values.hasNext()){ |
32 | String[] value = (String[])values.next(); |
33 | for ( int i = 0 ;i < value.length;i++){ |
40 | chain.doFilter(request, response); |
42 | public boolean sql_inj(String str) |
44 | String[] inj_stra=inj_str.split( "\\|" ); |
45 | for ( int i= 0 ; i < inj_stra.length ; i++ ) |
47 | if (str.indexOf( " " +inj_stra[i]+ " " )>= 0 ) |
也可以单独在需要防范SQL注入的JavaBean的字段上过滤:
7 | public static String TransactSQLInjection(String sql) { |
8 | return sql.replaceAll( ".*([';]+|(--)+).*" , " " ); |