• 防止XSS攻击的过滤器


    package com.jyc.common.filter;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    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;
    import javax.servlet.http.HttpServletResponse;
    import com.jyc.common.utils.StringUtils;

    /**
    * 防止XSS攻击的过滤器
    *
    * @author jianyongchao
    */
    public class XssFilter implements Filter
    {
    /**
    * 排除链接
    */
    public List<String> excludes = new ArrayList<>();

    /**
    * xss过滤开关
    */
    public boolean enabled = false;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
    String tempExcludes = filterConfig.getInitParameter("excludes");
    String tempEnabled = filterConfig.getInitParameter("enabled");
    if (StringUtils.isNotEmpty(tempExcludes))
    {
    String[] url = tempExcludes.split(",");
    for (int i = 0; url != null && i < url.length; i++)
    {
    excludes.add(url[i]);
    }
    }
    if (StringUtils.isNotEmpty(tempEnabled))
    {
    enabled = Boolean.valueOf(tempEnabled);
    }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
    {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (handleExcludeURL(req, resp))
    {
    chain.doFilter(request, response);
    return;
    }
    XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
    chain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response)
    {
    if (!enabled)
    {
    return true;
    }
    if (excludes == null || excludes.isEmpty())
    {
    return false;
    }
    String url = request.getServletPath();
    for (String pattern : excludes)
    {
    Pattern p = Pattern.compile("^" + pattern);
    Matcher m = p.matcher(url);
    if (m.find())
    {
    return true;
    }
    }
    return false;
    }

    @Override
    public void destroy()
    {

    }
    }
  • 相关阅读:
    痛苦之旅——安装Eric4
    如何把自己写的python程序给别人用
    (转)史上最好的Python线程指南
    (转)python编码问题
    Beautiful Soup的一些中文资料
    oracle监听配置
    redhat6.5安装oracle 11g
    《深入浅出MFC》– Document-View深入探讨
    CAS解扰小结
    ts包、表、子表、section的关系
  • 原文地址:https://www.cnblogs.com/qq3245792286/p/15469602.html
Copyright © 2020-2023  润新知