SpringBoot2.x Series tutorial 08 springboot integration filter and interceptor

Posted by nutshell on Mon, 03 Jan 2022 07:24:24 +0100

First of all, filters and interceptors are two different things conceptually. Filters depend on Servlet containers and are part of Servlet specifications, while interceptors exist independently and can be used in any case; In addition, filters and interceptors have the following differences.

1. The trigger timing of the filter is different from that of the interceptor. The filter is preprocessed after the request enters the container, but before the request enters the servlet. The request for lodging return is also processed by the servlet and before returning to the front end.

2. The interceptor can obtain all bean s in the IOC container, but the filter cannot, because the interceptor is provided and managed by spring, and the spring function can be used by the interceptor. Injecting a Service into the interceptor can call business logic, and the filter is the Java EE standard, which only needs to rely on the Servlet api and does not need to rely on spring

3. The implementation of filter is based on callback function, and the implementation of interceptor is based on reflection.

4. The life cycle of filters is managed by the Servlet container, while interceptors are usually executed by dynamic agents (reflection).

Difference between filter and interceptor

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3zggftsn-1627904239251)( https://segmentfault.com/img/bVcIzSn )]

Implementation of filter

The filter is mainly used to filter some business rules before the request reaches the corresponding controller, and its implementation is relatively simple. Here is a simple implementation case for the filter.

1. Filter implementation class

import javax.servlet.*;
import java.io.IOException;

public class Filter01 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        long end = System.currentTimeMillis();
        System.out.println("The total time spent is-time:"+(end-start)+"ms");
    }

    @Override
    public void destroy() {

    }
}

2. Filter configuration class

import com.kkcl.coding.filter.Filter01;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean registrationFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new Filter01());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("Filter01");
        registrationBean.setOrder(1);
        return registrationBean;
    }
}

3. Implementation of annotation

@WebFilter(urlPatterns ="/*", filterName ="logFilter2")
public class LogCostFilter2implements Filter {
    @Override
    public void init(FilterConfig filterConfig)throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {
        long start = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("LogFilter2 Execute cost=" + (System.currentTimeMillis() - start));
    }
 
    @Override
    public void destroy() {
 
    }
}


In addition, you need to add@ServletComponentScan("com.pandy.blog.filters")Notes.

Implementation of interceptor

The interceptor can be coupled with business code. In terms of actual function, the frequency used is slightly higher than that of the filter, and the implementation is also very familiar with the filter. Let's take a practical case for the interceptor.

1. Implementation class of interceptor

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Interceptor01 implements HandlerInterceptor {

    long start = System.currentTimeMillis();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        start = System.currentTimeMillis();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long end = System.currentTimeMillis();
        System.out.println("The total execution time is:"+ (end-start) + "ms");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2. Configuration class of interceptor

import com.kkcl.coding.interceptor.Interceptor01;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new Interceptor01()).addPathPatterns("/*");
    }
}

Summary

The above simply summarizes the implementation of springboot integrated filter and interceptor. In essence, it is not designed for any actual application scenarios. Later, it will be explained in detail for the actual application scenarios.

reference material

[1],https://segmentfault.com/a/1190000037755221
[2],https://www.cnblogs.com/paddix/p/8365558.html

Topics: Spring Boot