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