Druid filter过滤请求

来源:互联网 发布:中传在线 网络教育 编辑:程序博客网 时间:2024/06/08 06:52
  • 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();        }    }
原创粉丝点击