Druid filter过滤请求

  • web.xml配置
<filter>
        <filter-name>sessionFilter</filter-name>
        <filter-class>SessionFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>/login*</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>sessionFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • java代码

    private Set<String>  excludesPattern;

    protected PatternMatcher pathMatcher = new ServletPathMatcher();

    public static final String PARAM_NAME_EXCLUSIONS = "exclusions";

    public static String contextPath = "";
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();
        String url = httpRequest.getRequestURI();
        if (isExclusion(url)|) {
            chain.doFilter(request, response);
            return;
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        //读取web.xml配置的不需要进行拦截的请求
        String exclusions = config.getInitParameter(PARAM_NAME_EXCLUSIONS);
        if (exclusions != null && exclusions.trim().length() != 0) {
            excludesPattern = new HashSet<String>(Arrays.asList(exclusions.split("\\s*,\\s*")));
        }
        getContextPath(config.getServletContext());
        logger.info(contextPath);
    }


    //拦截过滤
    public boolean isExclusion(String requestURI) {
        if (excludesPattern == null) {
            return false;
        }
        if(requestURI.equals(contextPath)){
            return true;
        }
        if (contextPath != null && requestURI.startsWith(contextPath)) {
            requestURI = requestURI.substring(contextPath.length());
            if (!requestURI.startsWith("/")) {
                requestURI = "/" + requestURI;
            }
        }
        for (String pattern : excludesPattern) {
            if (pathMatcher.matches(pattern, requestURI)) {
                return true;
            }
        }
        return false;
    }

    //获取根路径
    public void getContextPath(ServletContext context) {
        if (context.getMajorVersion() == 2 && context.getMinorVersion() < 5) {
            return;
        }
        try {
            String path = context.getContextPath();
            if (path == null || path.length() == 0) {
                path = "/";
            }
            contextPath = path;
        } catch (NoSuchMethodError error) {
            error.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值