Open In App

Spring MVC – Servlet Filter vs Handler Interceptor

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.).

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 (Handler) Interceptor

Below are the HandlerInterceptor methods.

HandlerInterceptor Methods:

  • preHandle(): Runs before to calling the target handler.
  • postHandle(): This function is called after the target handler but before the view is rendered by the DispatcherServlet.
  • afterCompletion(): Callback when request processing and display rendering being finished.

Create a HandlerInterceptor

The org.springframework.web.servlet.HandlerInterceptor interface must be implemented by a class before it can be used as a HandlerInterceptor.

LogFilter:

Java




@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 {
        logger.info("Hello from: " + request.getLocalAddr());
        chain.doFilter(request, response);
    }
}


LogInterceptor:

Java




public class LogInterceptor implements HandlerInterceptor {
  
    private Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
  
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
      throws Exception {
        logger.info("preHandle");
        return true;
    }
  
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 
      throws Exception {
        logger.info("postHandle");
    }
  
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 
      throws Exception {
        logger.info("afterCompletion");
    }
}


Difference between (Servlet) Filter and (Handler) Interceptor

Characteristics

(Servlet) Filter

(Handler) Interceptor

Definition

Every time an HTTP request or answer is received, the servlet container runs the Java class Filter.

An interceptor only permits custom post-processing with access to Spring Context and custom pre-processing with the possibility to forbid the handler’s execution.

Interface

jakarta.servlet.Filter

HandlerInterceptor

Execution order

Prior to/after servlets, servlet filters

Prior to or following controller technique, spring interceptorswon’t start operating until after Filters.

Level of operation

Filter operates on Servlet level.

Interceptor operates on Controller level.

Method

Compared to Interceptor’s postHandle, Filter’s doFilter technique is far more flexible. It is possible to modify the request or answer, forward it down the chain, or even stop the request from being processed.

Since you have access to the real target “handler,” a HandlerInterceptor provides more precise control than a filter. Even the handler method’s annotation status may be verified.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads