首页 > 编程学习 > Java 加Filter过滤器的时候一定记得设置编码格式
201311 月19

Java 加Filter过滤器的时候一定记得设置编码格式

package web;

import web.sys.Globals;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class SqlFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
	req.setCharacterEncoding("GBK");
        res.setCharacterEncoding("GBK");
        //获得所有请求参数名
        Enumeration params = req.getParameterNames();

        String sql = "";
        while (params.hasMoreElements()) {
            //得到参数名
            String name = params.nextElement().toString();
            //得到参数对应值
            String[] value = req.getParameterValues(name);
            for (int i = 0; i < value.length; i++) {
                sql = sql + value[i];
            }
        }

        //有sql关键字,跳转到error.html
        if (sqlValidate(sql)) {
            res.sendRedirect("/"+Globals.APP_BASE_NAME+"/include/404error.html");
            //String ip = req.getRemoteAddr();
        } else {
            chain.doFilter(req, res);
        }
    }

    //效验
    protected static boolean sqlValidate(String str) {
        str = str.toLowerCase();//统一转为小写
        String badStr = "and|exec|execute|insert|create|drop|table|from|grant|use|" +
                "group_concat|column_name|information_schema.columns|table_schema|" +
                "where|select|delete|update|order|by|*|chr|char" +
                "|declare|;|--|+|,|%|#";//过滤掉的sql关键字,可以手动添加  qxmore000400010009
        String[] badStrs = badStr.split("\\|");

        for (int i = 0; i < badStrs.length; i++) {
            if (str.indexOf(badStrs[i]) != -1) {

                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    public void destroy() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}

本文地址:https://wizzer.cn/archives/2769 , 转载请保留.

2 Responses to “Java 加Filter过滤器的时候一定记得设置编码格式”

  1. #1 回复 | 引用 Post:2013-11-28 22:52

    这个校验有问题的还没有察觉吗?

发表评论