【问题标题】:URL path matcher in java (Spring)java中的URL路径匹配器(Spring)
【发布时间】:2019-05-10 13:13:36
【问题描述】:

在我们的应用程序中,我们正在创建不应针对某些 url 命中的请求过滤器。我们希望能够排除像 spring do witch url patterns 这样的 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。

【问题讨论】:

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


    【解决方案1】:

    您可以使用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);
      }
    }
    

    【讨论】:

    • 正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2014-08-23
    • 1970-01-01
    • 2018-07-29
    • 2019-12-25
    相关资源
    最近更新 更多