Spring Boot interceptor, filter, listener

Using Web frameworks at work, you can't avoid dealing with these concepts, do a summary, and say interceptors, filters, and listeners in one go.

GitHub source address

1. Interceptor, filter, listener difference

  • Interceptor: Depends on the web framework, Java-based reflection mechanism, is an application of AOP. An interceptor instance can be called multiple times during a controller lifetime. Only the request of the Controller can be intercepted.
  • Filter: Depends on the Servlet container, based on the function back, can filter almost all requests, a filter instance can only be called once in the container.
  • Listener: A web listener is a special class in a servlet that listens for specific events of the web, starts when the web application starts, and only initializes once.

2. What is the use?

  • Interceptor: When a request is in progress, you want to intervene in its progress, or even control whether it terminates. This is what the interceptor does.
  • Filter: When there is a bunch of things, just want to choose something that matches. The tool that defines these requirements is the filter.
  • Listener: After an event occurs, you only want to get the details of the events happening without interfering with the execution of the event. This uses the listener.

3. Startup sequence

Listener > Filter > Interceptor

4. The specific implementation in SpringBoot

(1) Interceptor

  1. Interceptors are commonly used in two ways to implement
    • Implement the HandlerInterceptor interface
    • Inherit HandlerInterceptorAdapter abstract class
  2. Difference and connection
  • HandlerInterceptorAdapter implements the AsyncHandlerInterceptor interface, and the AsyncHandlerInterceptor interface inherits the HandlerInterceptor interface.
  • The AsyncHandlerInterceptor interface has an afterConcurrentHandlingStarted method.
  1. specific method
  • preHandle //The method to go first after requesting return true Continue to execute
  • postHandle // before returning after request
  • afterCompletion //after processing is complete
  • afterConcurrentHandlingStarted // If a variable of type current is returned, a new thread is enabled. After the preHandle method is executed, afterConcurrentHandlingStarted is called, and then the new thread executes preHandle, postHandle, afterCompletion
  1. Code

[Note] The following code is based on springboot2.0

(1) Interceptor

MyInterceptor1 inherits HandlerInterceptorAdapter

MyInterceptor2 implements the HandlerInterceptor interface

public class MyInterceptor1 extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime", System.currentTimeMillis());
        System.out.println(">>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (long) request.getAttribute("startTime");
                 System.out.println("MyInterceptor1 Execution:" + (System.currentTimeMillis() - startTime));
        System.out.println(">>>>> MyInterceptor1 postHandle >>>>>>>>>>>>>>>>>>>>>>");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        request.removeAttribute("startTime");
        System.out.println(">>>>> MyInterceptor1 afterCompletion >>>>>>>>>>>>>>>>>>>>>>");
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
        System.out.println(">>>>> MyInterceptor1 afterConcurrentHandlingStarted >>>>>>>>>>>>>>>>>>>>>>");
    }
}
public class MyInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime", System.currentTimeMillis());
        System.out.println(">>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (long) request.getAttribute("startTime");
                 System.out.println("MyInterceptor2 Execution:" + (System.currentTimeMillis() - startTime));
        System.out.println(">>>>> MyInterceptor2 postHandle >>>>>>>>>>>>>>>>>>>>>>");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        request.removeAttribute("startTime");
        System.out.println(">>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>>>>>>>");
    }
}

(2) Configuration

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

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

(3) Request

@RestController
@SpringBootApplication
public class SpringbootInterceptorApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootInterceptorApplication.class, args);
    }


    @GetMapping(value = "/hello1")
    public ResponseEntity<String> hello() throws InterruptedException {
        Thread.sleep(500);
        return ResponseEntity.ok("HelloWorld");
    }

    @GetMapping(value = "/hello2")
    public StreamingResponseBody hello2() throws InterruptedException {
        Thread.sleep(500);
        return (OutputStream outputStream) -> {
            outputStream.write("success".getBytes());
            outputStream.flush();
            outputStream.close();
        };
    }

    @GetMapping(value = "/hello3")
    public Future<String> hello3() throws InterruptedException {
        Thread.sleep(500);
        return new AsyncResult<>("Hello");
    }
}

(4) Operation results

  1. Request /hello1

    >>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>
     MyInterceptor2 execution: 516
    >>>>> MyInterceptor2 postHandle >>>>>>>>>>>>>>>>>>>>>
     MyInterceptor1 execution: 516
    >>>>> MyInterceptor1 postHandle >>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>
    >>>>> MyInterceptor1 afterCompletion >>>>>>>>>>>>>>>>
    

    Execute by pressing preHandle > postHandle > afterCompletion

  2. Request /hello2 or /hello3

    >>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor1 afterConcurrentHandlingStarted >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>
     MyInterceptor2 execution: 1
    >>>>> MyInterceptor2 postHandle >>>>>>>>>>>>>>>>>>>>>>
     MyInterceptor1 execution: 1
    >>>>> MyInterceptor1 postHandle >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>>>>>>>
    >>>>> MyInterceptor1 afterCompletion >>>>>>>>>>>>>>>>>>>>>>
    

    MyInterceptor1 execution order preHandle > afterConcurrentHandlingStarted > preHandle > postHandle >afterCompletion

    MyInterceptor2 execution order preHandle > preHandle > postHandle > afterCompletion

In summary. For the return value of the concurrent type, spring will enable a new thread to handle the concurrent type message, and the preHandle method will be called again in the new thread.

(2) Filter

(1) Filter

public class MyFilter1 implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(filterConfig.getInitParameter("initParam"));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter1 >>>>>>>>>>>");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

(2) Configuration

  • First way
@Bean
public FilterRegistrationBean<MyFilter1> filterRegistrationBean() {
    FilterRegistrationBean<MyFilter1> filterRegistrationBean = new FilterRegistrationBean<>();
    filterRegistrationBean.addUrlPatterns("/*");//Filter all
    filterRegistrationBean.setFilter(new MyFilter1());
    filterRegistrationBean.setOrder(1);
    filterRegistrationBean.addInitParameter("initParam", "initOk");
    return filterRegistrationBean;
}
  • Second way
@Bean
public MyFilter1 myFilter() {
    return new MyFilter1();
}
  • Third way
@WebFilter("/test/*")
public class MyFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter2");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("DoFilter 2");
    }
}

By @WebFilter("/test/*") annotation, you first need @ServletComponentScan("com.jiuxian")

Filter global interception configuration (/*) and Interceptor (/**) are different need to pay attention

(3) Listener

(1) Listener

public class MyListener1 implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("MyListener1 ... ");
    }
}

(2) Configuration mode is similar to Filter

  • First way
 @Bean
public ServletListenerRegistrationBean<MyListener1> registrationBean() {
    ServletListenerRegistrationBean<MyListener1> servletListenerRegistrationBean
            = new ServletListenerRegistrationBean<>();
    servletListenerRegistrationBean.setListener(new MyListener1());
    return servletListenerRegistrationBean;
}
  • Second way
@Bean
public MyListener1 myListener1() {
    return new MyListener1();
}
  • Third way
@WebListener
public class MyListener2 implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("MyListener2");
    }
}

To use the @WebListener annotation, you first need @ServletComponentScan("com.jiuxian")

[Note] The above code is based on springboot2.0

GitHub source address

Intelligent Recommendation

Getting Started with Spring Boot - Advanced (1) - Servlet, Filter, Listener, Interceptor

User authentication and authorization, logging MDC, codec, UA check, multi-end correspondence, etc. all need to be handled by interception request. In this case, Filter, Listener and Interceptor are r...

Spring Boot introductory tutorial (20): Filter, Listener, Servlet, Interceptor

One: Filter Declare the filter and use the @ServletComponentScan annotation in Application Two: Listener 1. ServletContextListener The contextInitialized() method is executed when the application star...

spring boot (7) three major java devices (filter, listener and interceptor)

  pom.xml  application.properties   index.html   Application.java   filter MyFilter.java   interceptor WebAppConfig.java    MyInterceptor.java   MyHandlerInterceptorAdapter.java   listener MyServ...

Spring-boot learning note (3) Write servlet, filter, listener, interceptor

Foreword We need to add annotations @ServletComponentscan on Spring-Boot startup before writing filters, listeners, and interceptors. Servlet Spring-boot write filters and Spring is similar, direct vi...

Spring Boot Custom Registration Servlet, Filter, Listener, Interceptor

I. Introduction Web.xml has been removed in Spring Boot, if you need to register Add servlet, filter, listener is Spring Bean, there are two ways in Spring Boot: Use the Servlet 3.0 API @ WebServlet, ...

More Recommendation

Lesson 6 Learning Spring boot from scratch (filter Filter, listener Listener, interceptor HandlerInterceptor)

filter(Filter)withListener (Listener)'S registration method andServlet Similarly, if you are unclear, you can check the previous article.This article will be used directly@WebFilterwith@WebListen...

spring project-filter, interceptor, listener

First, the order of HTTP request background execution Start sequence: listener> filter> interceptor (context-param-->listener-->filter-->servlet-->interceptor) Memory skills: Receive...

Spring boot interceptor Filter

background: In fact, it is necessary to complete a simple security verification of the calling interface. It seems that it is relatively easy to find out the signature algorithm. After all, the hmac a...

Spring boot filter, interceptor

Filter FILTER is part of the servlet container, part of the Servlet specification, The interceptor is independent, which can be used in any case. Article catalog Filter filter FilterRegistrationBean m...

Filter and interceptor in Spring-Boot

1. Filter In fact, the filter (Filter) is very similar to Servlet, which is a component of Java. That is, before sending to Servlet, you can intercept and process the request, or you can deal with the...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top