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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With