제이온

[Spring] What are Filter, Interceptor, and Argument Resolver?

Created: 2024-04-27

Created: 2024-04-27 00:41

What is a Filter?

A filter is a feature of the J2EE standard specification that provides the ability to handle additional tasks for all requests matching a URL pattern before/after the request is delivered to the Dispatcher Servlet. In other words, it is managed by a web container like Tomcat, not the Spring container, and processes the request before it reaches the Dispatcher Servlet.


[Spring] What are Filter, Interceptor, and Argument Resolver?


Filter Implementation

To add a filter, you must implement the Filter interface from javax.servlet, which has the following three methods.


  • init method
    • This method initializes the filter object and adds it to the service. The web container calls the init method once to initialize the filter object, and subsequent requests are handled through the doFilter() method.
  • doFilter method
    • This method is executed by the web container before any HTTP request matching the url-pattern is delivered to the Dispatcher Servlet and before the Dispatcher Servlet sends an HTTP response to the client.
      The doFilter() parameter includes FilterChain, which delivers the request to the next destination through FilterChain's doFilter(). By inserting the necessary processing steps before and after chain.doFilter(), the desired processing can be performed.
  • destroy method
    • This method removes the filter object from the service and returns the resources it uses. It is called once by the web container, after which it is no longer handled by doFilter().


Example Code - Servlet Specification


Example Code - @Component


  • @Component: Allows registering the Filter as a Spring bean.
  • @Order: Allows defining the order when multiple filters are used.
  • When a filter corresponding to the servlet specification is registered as a Spring bean in this way, other beans corresponding to the Spring specification can be used.


Example Code - @Configuration

If you want to make the filter work only for specific URIs, you can register the filter as a Spring bean using FilterRegistrationBean.


Filter Usage

It primarily handles the validation and processing of request parameters themselves.


  • Common security tasks
    • Since filters operate within the web container, security checks (such as XSS and CSRF prevention) can be performed to block invalid requests. Because requests are blocked before they reach the Spring container, security can be further enhanced.
  • Logging for all requests
  • Image/data compression and character encoding
    • Filters have implemented features commonly used in web applications, such as image or data compression and character encoding.
  • ServletRequest customization
    • HttpServletRequest can only read the contents of the Body once. Therefore, Filter or Interceptor cannot read the Body. A custom ServletRequest can be created to log the Body.


Interceptor

What is an Interceptor?

Unlike filters, which are part of the J2EE standard specification, an Interceptor is a Spring-provided technology that allows you to reference or manipulate requests and responses before and after the Dispatcher Servlet calls a controller. In other words, unlike filters that operate in the web container, interceptors operate within the Spring context.


The Dispatcher Servlet requests that the appropriate controller be found through handler mapping, and returns the execution chain as a result. So, if one or more interceptors are registered in this execution chain, they are executed sequentially before the controller is executed. If there are no interceptors, the controller is executed immediately.


Interceptor Implementation

To add an interceptor, you must implement the org.springframework.web.servlet.HandlerInterceptor interface, which has the following three methods.


  • preHandle method
    • The preHandle method is executed before the controller is called. Therefore, it can be used for pre-processing tasks that need to be performed before the controller, or for manipulating or adding request information.
    • The third parameter of the preHandle method, the handler parameter, is an object that abstracts the information of the method annotated with @RequestMapping.
    • The return type of the preHandle method is boolean. If the return value is true, the process continues to the next stage. If it is false, the process is stopped, and subsequent tasks (the next interceptor or controller) are not executed.
  • postHandle method
    • The postHandle method is executed after the controller is called. Therefore, it can be used when there are post-processing tasks to be performed after the controller.
  • afterCompletion method
    • As its name suggests, the afterCompletion method is executed after all tasks are completed, including the generation of final results from all views.


Example Code


  • Register the created interceptor as a bean.
  • Register the created interceptor in the addInterceptors() method of the WebMvcConfigurer interface.
  • Interceptors operate in the order they are registered in the InterceptorRegistry.


Interceptor Usage

It primarily handles request information consistency processing using service logic.


  • Common tasks like authentication/authorization
    • For example, tasks related to client requests, such as authentication or authorization, can be checked before they are passed to the controller.
  • Logging API calls
    • You can record client information through the received HttpServletRequest and HttpServletResponse objects.
  • Processing data passed to the Controller
    • You can process the received HttpServletRequest and HttpServletResponse objects and pass them to the controller.
  • Mimicking AOP
    • You can obtain additional information, such as the signature of the method to be executed, through the third parameter HandlerMethod of the preHandle() method, and determine whether to execute the logic based on this information.


Filter vs Interceptor

  • Filters run in the web context, while interceptors run in the Spring context, so their execution timing differs.
  • Filters can handle before and after the Dispatcher Servlet, while interceptors can handle before and after the Controller.
  • Filters are better suited for tasks that need to be handled globally regardless of Spring, or for validating input parameters themselves, or when using ServletRequest instead of HttpServletRequest.
  • Interceptors are better suited for tasks that need to be handled globally related to client requests within Spring, or when service logic needs to be mixed in.
  • Interceptors can use @ControllerAdvice and @ExceptionHandler for exception handling, but filters cannot.
    • Filters typically wrap the doFilter() method in a try-catch block to handle exceptions that occur at that point immediately.


Argument Resolver

What is Argument Resolver?

Argument Resolver can indirectly help create the desired object from the values received in a request when a request comes to the controller.


Argument Resolver Usage

For example, let's assume that a request comes with a JWT token. We need to verify whether this token is a valid token, and then extract the id stored in the token and create it as a logged-in user object.

If Argument Resolver is not used in this case, the process of verifying the token and converting it to a logged-in user object must be implemented in each controller. This would result in duplicate code in controllers that require user verification, and increase the responsibility of the controllers. Argument Resolver can solve this problem.


Argument Resolver Implementation

ArgumentResolver can be used by implementing HandlerMethodArgumentResolver. And this interface specifies that the following two methods should be implemented.



  • supportsParameter method
    • A specific annotation is created and attached to the front of the Parameter for which you want the ArgumentResolver to be executed. The supportsParameter() method checks if the requested method's argument has the desired annotation attached and returns true if it contains the desired annotation.
  • resolveArgument method
    • If supportsParameter receives true, i.e., if a method with a specific annotation exists, this method binds the parameter to the desired form and returns it.


When using ArgumentResolver in this way, the implementation of the controller is as follows.



Difference between Argument Resolver and Interceptor

  • ArgumentResolver operates after the interceptor and returns the desired object from the values received in the request when a request comes to the controller.
  • On the other hand, the interceptor intercepts the request before the actual controller is executed and cannot return a specific object. Only boolean or void return types exist.


References


Expected Interview Questions and Answers

What is a Filter?

A filter provides the ability to handle additional tasks for all requests matching a URL pattern before/after the request is delivered to the Dispatcher Servlet and operates at the servlet container level.


When is a Filter used?

Filters can handle tasks that need to be processed globally, regardless of Spring. They are also used when validating request parameters.

Specifically, they handle common security tasks, logging for all requests, image/data compression and character encoding, and ServletRequest customization tasks.


What is an Interceptor?

An interceptor provides the ability to reference or manipulate requests and responses before and after the Dispatcher Servlet calls a controller, operating within the Spring container.


When is an Interceptor used?

Interceptors can handle tasks that need to be processed globally related to client requests and are mainly used when calling service logic during validation.

Specifically, they handle common tasks like authentication/authorization, logging API calls, and processing data passed to the Controller.


What is the difference between a Filter and an Interceptor?

Filters run in the servlet container, while interceptors run in the Spring container.

Filters can handle before and after the Dispatcher Servlet, while interceptors can handle before and after the Controller.

Therefore, filters are best suited for tasks that need to be handled globally regardless of Spring, and interceptors are best suited for tasks that need to be handled globally related to client requests.


What is Argument Resolver?

Argument Resolver indirectly helps create the desired object from the values received in a request when a request comes to the controller.


When is Argument Resolver used?

It can be used when a request comes with a JWT token, to verify whether the token is valid, and then extract the id stored in the token and create it as a LoginMember object.


What is the difference between an Interceptor and Argument Resolver?

Argument Resolver returns the desired object from the values received in the request when a request comes to the controller. On the other hand, interceptors cannot return objects in this way, and Argument Resolver is executed after the interceptor is executed.

Comments0