Home > Java > javaTutorial > How to use Interceptor interceptor in SpringBoot

How to use Interceptor interceptor in SpringBoot

王林
Release: 2023-05-11 09:13:05
forward
1358 people have browsed it

Using interceptors in springboot is also relatively simple. Implement the HandlerInterceptor or AsyncHandlerInterceptor interface, and then add the interceptor from the configuration;

The AsyncHandlerInterceptor interface inherits HandlerInterceptor and has an afterConcurrentHandlingStarted method:

How to use Interceptor interceptor in SpringBoot

How to use Interceptor interceptor in SpringBoot

Methods in the interface:

  • preHandle: executed before the Controller, parameters can be determined , the executed controller method, etc., the return value is boolean, return true and continue running (the interceptor and controller below), otherwise start the return operation (execute the previous interceptor return and other operations);

  • postHandle: executed after the Controller and before the view returns. ModelAndView can be processed before returning;

  • afterCompletion: executed after the request is completed;

  • afterConcurrentHandlingStarted: This method will be called and run using a new thread only when the controller return value is java.util.concurrent.Callable;

There are two methods of execution order:

  • preHandle -> Execute Controller -> postHandle -> afterCompletion;

  • preHandle -> Execute Controller -> afterConcurrentHandlingStarted -> The callable thread executes the call() method -> new thread starts preHandle -> postHandle -> afterCompletion; (when the controller method returns the Callable object)

Configure the interceptor:

Implement the addInterceptors method in the WebMvcConfigurer interface, and use the parameter InterceptorRegistry object to add your own interceptor. You can add specified interception paths or remove certain filtering paths. You can also set the priority order of the interceptor, from small to large. Default 0;

Execution order of multiple interceptors:

The preHandle method is in order from small to large. After the controller is executed, other methods are in reverse order, similar to the filter. ;

Test startup class, default configuration:

/**
 * 2023年3月16日下午4:56:23
 */
package testspringboot.test9interceptor;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
/**
 * @author XWF
 *
 */
@SpringBootApplication
public class Test9Main {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(Test9Main.class, args);
    }
 
}
Copy after login

controller class:

/**
 * 2023年3月16日下午4:58:02
 */
package testspringboot.test9interceptor;
 
import java.util.concurrent.Callable;
 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author XWF
 *
 */
@RestController
@RequestMapping("/interceptor")
public class Test9Controller {
 
    @RequestMapping("/a")
    public String a(String s) {
        System.out.println(">>>a():" + s);
        return "OK";
    }
    
    @RequestMapping("/b")
    public Callable<String> b() {
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                System.out.println("call() thread id=" + Thread.currentThread().getId());
                Thread.sleep(2000);
                return "abcdefg";
            }
        };
        System.out.println(">>>b()");
        return callable;
    }
    
}
Copy after login

Two custom interceptors 1 and 2:

/**
 * 2023年3月16日下午5:14:14
 */
package testspringboot.test9interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * @author XWF
 *
 */
public class MyInterceptor1 implements HandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle 1, handler=" + handler);
        return request.getQueryString().length() < 10 ? true : false; 
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 1");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("afterCompletion 1");
    }
    
}
Copy after login
/**
 * 2023年3月16日下午5:15:28
 */
package testspringboot.test9interceptor;
 
import java.util.Date;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * @author XWF
 *
 */
@Component
public class MyInterceptor2 implements AsyncHandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle 2 " + new Date() + " ThreadId=" + Thread.currentThread().getId());
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 2");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("afterCompletion 2");
    }
    
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("afterConcurrentHandlingStarted 2 " + new Date());
    }
    
}
Copy after login

Configuration interception Device:

/**
 * 2023年3月16日下午5:20:31
 */
package testspringboot.test9interceptor;
 
import javax.annotation.Resource;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * @author XWF
 *
 */
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
 
    @Resource
    MyInterceptor2 myinterceptor2;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor1())
            .addPathPatterns("/interceptor/a")        //添加拦截路径,两种参数List<String>和String ...
            .excludePathPatterns("/interceptor/b")        //排除路径,两种参数List<String>和String ...
            .order(1);        //设置拦截器顺序,由小到大,默认0
        registry.addInterceptor(myinterceptor2);    //也可以使用spring管理的对象
    }
    
}
Copy after login

Send a post test request: http://192.168.1.30:8080/interceptor/a?s=hello, the order of interceptor 2 defaults to 0, the order of interceptor 1 is 1, preHandle 2 is executed first. After the controller is executed, the remaining Handles are executed first and then 2;

How to use Interceptor interceptor in SpringBoot

Send a request for preHandle to return false: http://192.168 .1.30:8080/interceptor/a?s=hello123456789, after the preHandle of interceptor 1 returns false, directly execute the afterCompletion of 2;

How to use Interceptor interceptor in SpringBoot

Send the test callable request: http ://192.168.1.30:8080/interceptor/b?s=hello, the interception path configuration skips interceptor 1 and only executes interceptor 2. You can see through threadid that two threads are used before and after;

How to use Interceptor interceptor in SpringBoot

The above is the detailed content of How to use Interceptor interceptor in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template