通用过滤器的写法

web.xml:


encoding-filter
com.demo.ParameterCharacterFilter

encoding
utf-8


contentType
text/html;charset=utf-8



resetEnable
false



allow
127.0.0.1



deny




filterurl

/lnb/test,/test




encoding-filter
/*

现在有 @WebFilter就方便多了,不用再配置xml了。

public class ParameterCharacterFilter implements Filter{
/运行访问IP列表/
public static final String PARAM_NAME_ALLOW = “allow”;

/*限制访问IP列表*/
public static final String  PARAM_NAME_DENY             = "deny";

/*不过滤URL地址*/
public static final String PARAM_NAME_NOURL             = "filterurl";

/*编码字符集*/
public static final String CONFIG_ENCODING                = "encoding";

/*编码类型*/
public static final String CONFIG_CONTENTTYPE            = "contentType";

/*是否启用IP控制*/
public static final String  PARAM_NAME_RESET_ENABLE     = "resetEnable";
private final static String TEMPLATE_PAGE_RESOURCE_PATH = "/template.html";
private boolean             statService;
public String               templatePage;

/**
 * 允许访问IP地址列表
 */
private List<IPRange>       allowList                   = new ArrayList<IPRange>();

/**
 * 禁止访问IP地址列表
 */
private List<IPRange>       denyList                    = new ArrayList<IPRange>();

/**
 * 不过滤URL地址列表
 */
private List<String>         nourlList                    = new ArrayList<String>();

private FilterConfig filterConfig;
private String encoding = "UTF-8";
private String contentType = null;

public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    templatePage = TEMPLATE_PAGE_RESOURCE_PATH;

    //读取字符编码
    try {
        String param = this.filterConfig.getInitParameter(CONFIG_ENCODING);
        if(param != null && param.trim().length() != 0){
            encoding = param.trim();
        }
    } catch (Exception e) {
        String msg = "initParameter config error, encoding : " + filterConfig.getInitParameter(CONFIG_ENCODING);
        logger.log(msg, Logger.LEVEL_ERROR);
    }

    //读取编码类型
    try {
        String param = this.filterConfig.getInitParameter(CONFIG_CONTENTTYPE);
        if(param != null && param.trim().length() != 0){
            contentType = param.trim();
        }
    } catch (Exception e) {
        String msg = "initParameter config error, contentType : " + filterConfig.getInitParameter(CONFIG_ENCODING);
        logger.log(msg, Logger.LEVEL_ERROR);
    }

    //读取是否启用状态
    try {
         String param = this.filterConfig.getInitParameter(PARAM_NAME_RESET_ENABLE);
         if (param != null && param.trim().length() != 0) {
             param = param.trim();
             boolean resetEnable = Boolean.parseBoolean(param);
             statService = resetEnable;
         }

    }catch (Exception e) {
        String msg = "initParameter config error, resetEnable : " + this.filterConfig.getInitParameter(PARAM_NAME_RESET_ENABLE);
        logger.log(msg, Logger.LEVEL_ERROR);
    }

    //读取可以访问的IP地址
    try {
        String param = this.filterConfig.getInitParameter(PARAM_NAME_ALLOW);
        if (param != null && param.trim().length() != 0) {
            param = param.trim();
            String[] items = param.split(",");
            for (String item : items) {
                if (item == null || item.length() == 0) {
                    continue;
                }

                IPRange ipRange = new IPRange(item);
                allowList.add(ipRange);
            }
        }
    } catch (Exception e) {
        String msg = "initParameter config error, allow : " + this.filterConfig.getInitParameter(PARAM_NAME_ALLOW);
        logger.log(msg, Logger.LEVEL_ERROR);
    }

    //读取禁止访问IP地址列表
    try {
        String param = this.filterConfig.getInitParameter(PARAM_NAME_DENY);
        if(param != null && param.trim().length() != 0){
            param = param.trim();
            String[] items = param.split(",");
            for(String item : items){
                if(item == null || item.length() == 0){
                    continue;
                }
                IPRange ipRange = new IPRange(item);
                denyList.add(ipRange);
            }
        }
    } catch (Exception e) {
        String msg = "initParameter config error, deny : " + this.filterConfig.getInitParameter(PARAM_NAME_ALLOW);
        logger.log(msg, Logger.LEVEL_ERROR);
    }

    //读取不过滤URL
    try {
        String param = this.filterConfig.getInitParameter(PARAM_NAME_NOURL);
        if(param != null && param.trim().length() != 0){
            param = param.trim();
            String[] items = param.split(",");
            for(String item : items){
                if(item == null || item.length() == 0){
                    continue;
                }
                nourlList.add(item.trim());
            }
        }
    } catch (Exception e) {
        String msg = "initParameter config error, url : " + this.filterConfig.getInitParameter(PARAM_NAME_NOURL);
        logger.log(msg, Logger.LEVEL_ERROR);
    }
}

public boolean isPermittedRequest(HttpServletRequest request) {
    String remoteAddress = request.getRemoteAddr();
    return isPermittedRequest(remoteAddress);
}

/**
 * 是否允许请求
 * @param remoteAddress
 * @return
 */
public boolean isPermittedRequest(String remoteAddress) {
    boolean ipV6 = remoteAddress != null && remoteAddress.indexOf(':') != -1;

    if (ipV6) {
        if (denyList.size() == 0 && allowList.size() == 0) {
            return true;
        }
    }

    IPAddress ipAddress = new IPAddress(remoteAddress);

    for (IPRange range : denyList) {
        if (range.isIPAddressInRange(ipAddress)) {
            return false;
        }
    }

    if (allowList.size() > 0) {
        for (IPRange range : allowList) {
            if (range.isIPAddressInRange(ipAddress)) {
                return true;
            }
        }

        return false;
    }

    return true;
}

/**
 * 验证用户访问URL是否不过滤
 * @param remoteUrl 当前用户访问URL
 * @return 如果不过滤URL列表中存在当前用户访问的URL则返回<code>true</code> 否则返回<code>false</code>
 */
public boolean isFilterUrl(String remoteUrl){
    if(nourlList.size() > 0){
        for(String item : nourlList){
            if(item.equals(remoteUrl)){
                return true;
            }
        }
    }
    return false;
}


public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    request.setCharacterEncoding(encoding);
    response.setContentType(contentType);
    HttpServletRequest req = (HttpServletRequest) request;
    String requestURI = req.getRequestURI();

    if(isFilterUrl(requestURI)){
        logger.log("Don't filter this URI: " + requestURI,Logger.LEVEL_DEBUG);
        filterChain.doFilter(request, response);
        return;
    }

    if(statService){
        //当前访问地址不在未过滤地址列表内

    }

    request = new Request((HttpServletRequest) request);

    filterChain.doFilter(request, response);
}



public void destroy() {
    filterConfig = null;
    encoding = null;
}

public static String stringFilter(String value) {
    // 只允许字母和数字
    // String regEx = "[^a-zA-Z0-9]";
    // 清除掉所有特殊字符
    //String regEx = "[`~!@$&*|''<>?~!@¥%……&*——|【】‘;’。%,?/]";
    String regEx = "'‘;’/";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(value);
    return m.replaceAll("").trim();
}


class Request extends HttpServletRequestWrapper {

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if(values == null)  return null;

        for (int i = 0; i < values.length; i++) {
            if(values[i] == null || "".equals(values[i])){
                continue;
            }

            String checkBefore = values[i];
            String checkAfter = StringUtils.stringFilter(values[i]);
            checkAfter = checkAfter.replaceAll("[^\\u0000-\\uFFFF]", "口");
            log.info("检查请求包含非法字符:"+checkBefore + ", 处理后为:" + checkAfter);
            values[i] = checkAfter;


        }

        return values;
    }

    @Override
    public String getParameter(String name) {
        String p = super.getParameter(name);
        if(p == null)
            return p;
        String value = StringUtils.stringFilter(p);
        return value.replaceAll("[^\\u0000-\\uFFFF]", "口");
    }

    public Request(HttpServletRequest request) {
        super(request);
    }


}

}

分享到 评论