Java中的URL路径匹配器(春季)

时间:2018-12-09 11:57:53

标签: java regex spring spring-security pattern-matching

在我们的应用程序中,我们正在创建请求过滤器,某些URL不应点击这些请求过滤器。我们希望能够排除类似于spring do witch URL模式的URL,例如:

// register filter in bean
FilterRegistrationBean filterBeanRegistration = new FilterRegistrationBean();
filterBeanRegistration.setFilter(myFilter());
filterBeanRegistration.addInitParameter("excluded", "*/foo/**, */bar/**");
...

并且新的过滤器不会匹配domain:8080/aaa/foo/xxxxdomain:8080/bbb/bar/xxxx之类的网址。

您能告诉我如何使用Spring类或其他简单方法吗?谢谢你的建议。

编辑: 我可以使用FilterBeanRegistration#addUrlPatterns(String... urls)方法指定url,但是没有任何格式可以指示应该点击哪个url。为了我们的目的,最好排除一些网址。

1 个答案:

答案 0 :(得分:3)

您可以使用org.springframework.web.filter.OncePerRequestFilter。每个传入请求都会执行一次。您可以覆盖shouldNotFilter方法以排除不需要过滤器运行的URL。示例代码:

public class MyFilter extends OncePerRequestFilter {

  private static final String[] excludedEndpoints = new String[] {"*/foo/**, */bar/**"};

  @Override
  protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    return Arrays.stream(excludedEndpoints)
        .anyMatch(e -> new AntPathMatcher().match(e, request.getServletPath()));
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    // Filtering logic goes here. call below line on successful authentication.
    filterChain.doFilter(request, response);
  }
}