Spring MVC (Servlet) Filter

Below are the Servlet Filter methods.

ServletFilter methods:

  • destroy(): When the filter is removed from the service, the destruct() function is only called once.
  • init(FilterConfig config): This function, init(FilterConfig config), is only used once. It serves as the filter’s initialization.
  • doFilter method (): Every time a user sends a request to any resource that the filter is mapped to, the doFilter method () is called. It is applied to jobs involving filtration.

Setting Up a (Servlet)Filter

First, we need to develop a class that implements the javax.servlet in order to establish a filter.Interface for filters:

Java




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
  
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
  
@Component
public class LogFilter implements Filter {
  
    private Logger logger = LoggerFactory.getLogger(LogFilter.class);
  
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
      throws IOException, ServletException {
        // Log information about the incoming request
        logger.info("Hello from: " + request.getLocalAddr());
  
        // Continue with the filter chain
        chain.doFilter(request, response);
    }
  
    // Other methods of the Filter interface (init, destroy) can be implemented if needed.
}


Spring MVC – Servlet Filter vs Handler Interceptor

Filter is a Java class that is executed by the Servlet Container for each incoming HTTP request and each HTTP response. Filter is associated with the Servlet API, while HandlerIntercepter is unique to Spring. Only after Filters will Interceptors begin to operate. HandlerInterceptors are appropriate for fine grained pre-processing duties (authorization checks, etc.).

Similar Reads

Spring MVC (Servlet) Filter

Below are the Servlet Filter methods....

Spring MVC (Handler) Interceptor

...

Difference between (Servlet) Filter and (Handler) Interceptor

Below are the HandlerInterceptor methods....

Contact Us