Interceptor achieve simple example SpringBoot

1 generates an interceptor class that implements the service interception

HandlerInterceptor implement interfaces, rewrite method preHandle

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("实现拦截操作,进入Controller之前执行/");
        return true;
    }

}

2 rewriting add interceptors in the configuration class file Method

WebMvcConfigurer implement interface addInterceptors rewriting process, process, or may be provided in the path does not intercept the intercepting

@Configuration  //等价于Spring的xml文件
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //定义需要拦截的数组
        String[] pathPatterns={
                "/**"
        };
        //定义不需要拦截的数组
        String[] excludePathPatterns={
                "/web/interceptor1"
        };
        InterceptorRegistration interceptor = registry.addInterceptor(new LoginInterceptor());
        interceptor.addPathPatterns(pathPatterns);
        interceptor.excludePathPatterns(excludePathPatterns);
    }
}

A simple interceptor is realized

Published 27 original articles · won praise 1 · views 852

Guess you like

Origin blog.csdn.net/weixin_44971379/article/details/104883490