Method of adding interceptor in springboot

Time:2021-9-17

Create interceptor

Create a class to implement the handleinterceptor interface (or inherit the abstract class that implements the interface), and implement the prehandle, posthandle and aftercompletion methods.

public class MyInterceptor implements HandlerInterceptor {

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

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        
    }

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

}

Where prehandle is executed before the controller method is executed. If false is returned, the request will be intercepted; The posthandle is executed after the request is processed and before the page is rendered, but the front and back-end separated projects should not be used very much at present; After completion is the execution after the request is completely processed after the page is rendered. It is usually used to release resources.

Create interceptor configuration class

Create a class to implement the webmvcconfiguration interface and add configuration annotations.

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {

    //The registered interceptor needs to be configured into the springboot container, otherwise the class injected in the interceptor will null pointer
    @Bean
    public MyInterceptor getMyInteceptpr(){
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getMyInteceptpr());
    }
}

If spring managed classes are injected into the interceptor, the interceptor needs to be added to the spring container. The method in the example is to add @ bean annotation, otherwise calling the managed classes directly will cause null pointer problems.
The addinterceptor can be followed by the addpathpatterns method to specify which methods will be intercepted. All requests are intercepted by default.

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]