Home > Software engineering >  How to add Conditional filters in springboot
How to add Conditional filters in springboot

Time:12-03

I have different filters in spring boot app that runs. I want to skip one filter from runing for few of the apis based on condition. I was able to do it by adding a condition in doFilterInternal. here the code for filter:


class ConditionalFilter extends OncePerRequestFilter {
  @Override
  protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
    HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
    if (!condition) {
        filterChain.doFilter(request, httpResponse);
    } else {
        someFilterLogic();
    }
  }
}

Is there any better way of doing it?

CodePudding user response:

The way you are doing it should be fine for class overriding Filter. But since you are using OncePerRequestFilter you can override the method shouldNotFilter as follows:

class ConditionalFilter extends OncePerRequestFilter {
  @Override
  protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
    someFilterLogic();
  }

  @Override
  protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    return condition; // replace with whatever condition you like
  }
}
  • Related