SpringBoot (eight) Interceptor Interceptor

    The previous article introduced the use of the Filter filter. When you mention the filter, you have to mention another thing called an interceptor. The functions of the two are similar, and both can realize the function of intercepting requests, but in fact there is a very big difference between the two. In this article, let's learn how to use interceptors.

    If you are a novice and have not read my previous series of SpringBoot articles, it is recommended to at least read this one:

SpringBoot (4) SpringBoot builds a simple server_springboot makes a service_heart poisoned blog-CSDN博客

    If you want to learn systematically from beginning to end, please pay attention to my SpringBoot column and keep updating:

https://blog.csdn.net/qq_21154101/category_12359403.html

Table of contents

1. Interceptor Interceptor​​​​​​

2. Custom Interceptor

3. Verify that the interceptor is in effect 

Four, multiple interceptors


1. Interceptor Interceptor​​​​​​

    Interceptors have a very similar function to filters. What filters can do, interceptors can do, or even better.

    Filter is a concept or component of Servlet, and Interceptor is a concept or component of Spring. Everyone knows that when doing web development, the most primitive time is not to use Spring or SpringBoot, but Jsp + servlet (I still remember when I was a junior in the computer room, I configured tomcat and Servlet there....). Both Spring and the subsequent SpringBoot are designed to simplify development, and we will not compare the two in detail here.

    Similarly, an interceptor is a component located between the client and the server, and can have 0-more than one, similar to a filter: 

2. Custom Interceptor

    SpringBoot provides support for interceptors and is very convenient to use. First, implement the HandlerInterceptor interface to create an interceptor. Here, only the implementation of the interceptor is simulated, and a very simple logic is written. If the request string contains "sb", it will be intercepted, otherwise it will be released:

package com.zhaojun.server.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 LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器处理中...");
        String queryString = request.getQueryString();
        if (queryString.contains("sb")) {
            System.out.println("拦截");
            return false;
        }
        System.out.println("放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器处理结束...");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求结束...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

    Next, you need to configure the interceptor, create a Config class, implement the WebMvcConfigurer interface, and add the @Configuration annotation:

package com.zhaojun.server.interceptor;

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 MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/login");
    }
}

3. Verify that the interceptor is in effect 

    Next, test whether the interceptor works. First, use a url that does not contain sb to request http://localhost:8080/login?name=zj&phone=156532890870&password=123456

       Look at the process of code execution: 

    It can be seen that the preHandle is first reached, because it does not contain the specific character sb, it is released. Then went to postHandle and afterCompletion in turn. And, because I continued to write the filter in the previous article, careful friends can see that the filter is executed before the interceptor.

    Next, use the url that contains the special character sb to make a request. http://localhost:8080/login?name=sb&phone=156532890870&password=123456

 

    It can be seen that because it contains a specific character sb, it is successfully intercepted in preHandle. In this way, because the interception is successful, the subsequent postHandlle and afterCompletion will naturally not be executed.

Four, multiple interceptors

    When learning filters, we can set multiple filters. As mentioned earlier, the interceptor can have 0-more than one. Next, we create another interceptor, the code directly copies the first one, just look at the execution process: 

package com.zhaojun.server.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 Interceptor2 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器2处理中...");
        String queryString = request.getQueryString();
        if (queryString.contains("sb")) {
            System.out.println("拦截");
            return false;
        }
        System.out.println("放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器2处理结束...");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求结束2...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

Correspondingly, this interceptor needs to be added to the Config class:

package com.zhaojun.server.interceptor;

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 MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/login");
        registry.addInterceptor(new Interceptor2());
    }
}

Use the url that does not contain sb and the url that contains sb to request respectively, and the execution process is as follows: 

    You can see some rules, and here is a brief summary:

(1) When the first interceptor does not intercept at preHandle, it will be executed sequentially to the preHandle of the second interceptor.

(2) If the second interceptor is not intercepted at preHandle, then execute postHandle and afterCompletion in reverse order.

(3) If the first interceptor does not intercept and the second interceptor intercepts, then the afterCompletion of the first interceptor will be executed directly.

(4) If the first interceptor intercepts, the subsequent interceptors will not execute again.

Guess you like

Origin blog.csdn.net/qq_21154101/article/details/131742473