【SpringBoot】Introduction to filters, listeners, and interceptors

1. Introduction

insert image description here

insert image description here

We can understand the characteristics of interceptors and filters through two pictures

1. Filter

The filter is preprocessed after the request enters the tomcat container, but before the request enters the servlet. The return of the request is also after the servlet is processed and before it is returned to the front end.

Understanding the above sentence, we can know that before entering the servlet, there are mainly two parameters: ServletRequest, ServletResponse Then what can we do with these two tests?

We can get HttpServletRequest through ServletRequest, then you can intercept requests or responses (Request, Response) to all web resources managed by the web server: such as Jsp, Servlet, static image files or static html files, etc. So as to achieve some special functions. For example, it implements some advanced functions such as URL-level permission access control, filtering sensitive words, compressing response information, and unifying character sets. It is mainly used to pre-process user requests, and can also post-process HttpServletResponse. The complete process of using Filter: Filter preprocesses the user request, then passes the request to the Servlet for processing and generates a response, and finally Filter performs post-processing on the server response. . It is started when your web application starts, it is only initialized once, and related requests can be intercepted in the future, and it will only be destroyed when your web application is stopped or redeployed. (It will be destroyed after each hot deployment).

2. Interceptor

From the above figure, we can see that the filter only works before and after the servlet, so it can neither catch exceptions, obtain bean objects, etc. These can only be done by interceptors entering the servlet. Interceptors are used to intercept a method or field before it is accessed and then add some operations before or after it. Such as logs, security, etc. Generally, interceptor methods are implemented through dynamic proxy. It can be used to verify permissions, or to determine whether the user is logged in, or to determine whether the current time is the ticket purchase time like 12306.

By comparison, we can actually find that the interceptor can do everything that the filter can do, and the filter does not necessarily do what the second interceptor can do.

3. Listener

A listener is a special class defined in the servlet specification. Used to monitor the creation and destruction events of domain objects such as servletContext, HttpSession and servletRequest. Listen to the event that the properties of the domain object are modified. It is used to do some necessary processing before and after the event occurs. It can be mainly used in the following aspects:

  • 1. Count the number of online users and online users
  • 2. Load initialization information when the system starts
  • 3. Statistical website visits
  • 4. Record user access path.

Commonly used listeners servletContextListener, httpSessionListener, servletRequestListener)

2. How to create

1. Filter

Custom Filter Use Servlet3.0 annotations to configure @WebFilter in the third step is the annotation of 3.0

1) Add @ServletComponentScan in the startup class to scan

2) Create a new Filter class, implements Filter, and implement the corresponding interface

3) @WebFilter marks a class as filter, which is scanned by spring

urlPatterns: interception rules, support regular

4) Control the call of the chain.doFilter method to realize whether to pass or not, web application resp.sendRedirect("/index.html"); Scenario: permission control, user login (non-front-end and back-end separation scenarios), etc.

application class

@SpringBootApplication
@ServletComponentScan
public class SpringbootstudyApplication {
    
    

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

LoginFilter filter

//过滤器拦截路径
@WebFilter(urlPatterns = "/api/*", filterName = "loginFilter")
public class LoginFilter  implements Filter{
    
    
          
     /**
      * 容器加载的时候调用
      */
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
    
    
          System.out.println("拦截器进入========拦截器进入========");
      }
      
      /**
       * 请求被拦截的时候进行调用
       */
      @Override
      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
          System.out.println("拦截中========拦截中========");

          HttpServletRequest hrequest = (HttpServletRequest)servletRequest;
          HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
          if(hrequest.getRequestURI().indexOf("/index") != -1 ||
                  hrequest.getRequestURI().indexOf("/asd") != -1 ||
                  hrequest.getRequestURI().indexOf("/online") != -1 ||
                  hrequest.getRequestURI().indexOf("/login") != -1
                  ) {
    
    
              filterChain.doFilter(servletRequest, servletResponse);
          }else {
    
    
              wrapper.sendRedirect("/login");
          }
          
      }

      /**
       * 容器被销毁的时候被调用
       */
      @Override
      public void destroy() {
    
    
          System.out.println("拦截器销毁========拦截器销毁========");
      }

}

1. Official website address: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners

2. Listener

@WebListener
public class RequestListener implements ServletRequestListener {
    
    

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
    
    
        // TODO Auto-generated method stub
        System.out.println("======销毁监听器========");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
    
    
        System.out.println("======进入监听器========");
        
    }

3. Interceptor

CustomWebMvcConfigurer main interceptor requires:

1:添加@Configuration注解

2:实现WebMvcConfigurer接口
//主拦截器,根据拦截不同路径跳转不同自定义拦截器 (实现WebMvcConfigurer方法)
@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer  {
    
    

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    

        registry.addInterceptor(new LoginIntercepter()).addPathPatterns("/api1/*/**");
        registry.addInterceptor(new TwoIntercepter()).addPathPatterns("/api2/*/**");
        
        //.excludePathPatterns("/api2/xxx/**"); //拦截全部 /*/*/**
        
        WebMvcConfigurer.super.addInterceptors(registry);
    }

}

LoginIntercepter sub-interceptor

public class LoginIntercepter implements HandlerInterceptor{
    
    

    /**
     * 进入controller方法之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("LoginIntercepter------->preHandle");

//        String token = request.getParameter("access_token");
//        
//        response.getWriter().print("fail");
        
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 调用完controller之后,视图渲染之前
     */
    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    
    
        
        System.out.println("LoginIntercepter------->postHandle");
        
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 整个完成之后,通常用于资源清理
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    
    
        System.out.println("LoginIntercepter------->afterCompletion");
        
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
    
    
}

TwoIntercepter ditto

3. Summary

Finally, let's unpack them:

Filter: used for attribute screening and object collection (the attribute and behavior of the filter object cannot be changed)

Listener: used for object monitoring and behavior recording (the properties and behavior of the listening object cannot be changed)

Interceptor: used for object interception, behavior intervention (can change the properties and behavior of the intercepted object)

Guess you like

Origin blog.csdn.net/weixin_44816664/article/details/130601054