Denis Stephanov
Denis Stephanov

Reputation: 5281

URL path matcher in java (Spring)

in our application we are creating request filters which should not be hit for some urls. We want be able to exclude urls like spring do witch url patterns, e.g.:

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

and new filter doesn't hit urls like domain:8080/aaa/foo/xxxx, domain:8080/bbb/bar/xxxx .

Can you tell me how to do that with spring classes or another simple way? Thank you in advice.

EDIT: There is FilterBeanRegistration#addUrlPatterns(String... urls) method where I can specify urls, but there is no any format which tells which url should hit. For our purposes is better exclude some urls.

Upvotes: 1

Views: 8645

Answers (1)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

You can use org.springframework.web.filter.OncePerRequestFilter. It gets executed once every incoming request. You can override shouldNotFilter method to exclude the URLs you don't want the filter to run for. Example code:

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);
  }
}

Upvotes: 12

Related Questions