Use filters and interceptors in spring MVC and spring boot to analyze the relationship and differences between filters, interceptors and AOP

The framework brings a lot of convenience to our development, and the use of many previously learned knowledge will be slightly different in the framework. This article mainly describes the use of filters and interceptors in the framework, and analyzes the relationship and differences between filters, interceptors and AOP

filter

The function of the filter is to intercept the path matching request, and then process the request accordingly, and then release the request to execute the original processing logic.

When there are multiple filters, a filter chain will be formed and executed one by one. It will be intercepted by the filter only when the request path matches

use

Create a class, implement the Filter interface, and override the doFilter() method

@Slf4j
public class TimeFilter implements Filter {
    private SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S");
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("TimeFilter Time of interception:{}",simpleDateFormat.format(new Date(System.currentTimeMillis())));
        chain.doFilter(request, response);
        log.info("After executing the request processing logic, return to TimeFilter Time of:{}",simpleDateFormat.format(new Date(System.currentTimeMillis())));
    }
}

Create a configuration class, use the method to create a filter and put it into the container

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public FilterRegistrationBean TimeFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        TimeFilter timeFilter = new TimeFilter();
        filterRegistrationBean.setFilter(timeFilter);
        // Add intercept path
        filterRegistrationBean.addUrlPatterns("/filter/*");
        Set<String> path = new HashSet<>();
        // Multipath condition
        // path.add("/filter/test1");
        // path.add("/filter/test2");
        // filterRegistrationBean.setUrlPatterns(path);
        // Sets the execution order of the filter
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }
}
test

Request interface and view log information

You can see from the log information that the request was successfully intercepted by the filter

Interceptor

Interceptors also intercept according to the request path. Interceptors, similar to Aop, are implemented in proxy mode. They can operate before and after the execution of the interface methods you need to access. In the framework, you can create interceptors by implementing the HandlerInterceptor interface. You need to override the three methods of preHandle(), postHandle(), and afterCompletion().

use

Create a class that implements the HandlerInterceptor interface and overrides the preHandle(), postHandle(), and afterCompletion() methods

@Slf4j
@Component
public class TimeInterceptor implements HandlerInterceptor {
    private SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S");
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("call TimeInterceptor Medium preHandle()Method time:{}",simpleDateFormat.format(new Date(System.currentTimeMillis())));
        // Only when the return value is true can the postHandle() and afterCompletion() methods continue to be executed. If false, the request ends and will not be executed again
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("call TimeInterceptor Medium postHandle()Method time:{}",simpleDateFormat.format(new Date(System.currentTimeMillis())));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("call TimeInterceptor Medium afterCompletion()Method time:{}",simpleDateFormat.format(new Date(System.currentTimeMillis())));
    }
}

In the configuration class, add the interceptor to the container and set the interception path

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private TimeInterceptor timeInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor).addPathPatterns("/interceptor/*");
//        Multipath configuration
//        List<String> path = new ArrayList<>();
//        path.add("/interceptor/test1");
//        path.add("/interceptor/test2");
//        registry.addInterceptor(timeInterceptor).addPathPatterns(path);
    }
}
test

Request interface and view log information

You can see from the log that the interceptor has successfully intercepted the request and executed three methods

Filter, interceptor, Aop

Execution sequence

When the filter, interceptor and AOP are all used for the interface method of a request path, the execution order is filter - "interceptor -" AOP "

effect

Main function of filter
  • User access processing
  • Set character set garbled processing
  • Filter sensitive words and compress response information
Main functions of interceptors
  • It can only intercept requests and access objects such as context. It is powerful. A request can be intercepted multiple times.
  • User access processing
  • Registration log
Main role of AOP
  • Logging

  • Performance statistics

  • safety control

  • transaction processing

  • exception handling

Can only be applied to bean s managed by the Spring container

In general, the earlier the data is filtered and intercepted, the smaller the impact on the service performance. When writing relatively common code, give priority to the filter, then the interceptor, and finally the AOP

difference
  • The interception of filter and interceptor is realized by matching the request path, while AOP (aspect oriented) interception can be tangential to packages, classes, method names, parameters, etc. through tangent points

  • Like interceptors, Spring AOP is an implementation of AOP, which is implemented in proxy mode

  • Aop can intercept packages, classes, method names and parameters, which is more flexible than intercepting them. Aop can implement more complex business logic for specific code

  • Interceptors are only responsible for action s. The role level is generally located in the Controller layer. Spring AOP is mainly used to intercept access to beans managed by spring. The general role is the same as that of the Service layer

reference resources

Spring filter interceptor AOP differences

Explain the differences between filters, interceptors and AOP in the most detail

If there are any mistakes or misunderstandings in this article, please help point them out. Thank you

Keywords: Java Spring Spring Boot AOP Spring MVC

Added by itsmeArry on Fri, 14 Jan 2022 00:50:56 +0200