Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Conditional filters in springboot

Tags:

spring-boot

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?

like image 767
Newbiedebeloper Avatar asked Sep 21 '25 00:09

Newbiedebeloper


1 Answers

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
  }
}
like image 60
deepakchethan Avatar answered Sep 22 '25 12:09

deepakchethan